This commit is contained in:
commit
db5ca7790d
47 files changed
+5882
-1134
No files matched your search
@@ -72,3 +72,6 @@ miniprogram/project.private.config.json
|
||||
|
||||
# Locally built BrowserSkill runtime and extension bundles
|
||||
/artifacts/browserskill/
|
||||
|
||||
# Local DuckDB extension extraction scratch dir (training template debugging)
|
||||
tmp-extract-duckdb/
|
||||
Binary file not shown.
+240
-128
@@ -3,11 +3,11 @@
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 产品模块 | Academy 企业培训(AIDO → 企业培训)· 培训计划管理 |
|
||||
| 文档版本 | v1.0 |
|
||||
| 编写日期 | 2026-11-10 |
|
||||
| 文档版本 | v1.1(按系统工程代码实际功能逻辑校准) |
|
||||
| 编写日期 | 2026-11-17(v1.0:2026-11-10) |
|
||||
| 关联文档 | 《企业培训系统-Academy落地方案》(docs/design)、《企业培训模块完整落地方案》(docs/pca) |
|
||||
| 关联代码 | `frontend/src/views/training/`(计划排期 PlanPanel、课程 CoursePanel、驾驶舱 DashboardPanel)、`internal/handler/training/`、`internal/application/service/training*.go`、`internal/router/routes_training.go` |
|
||||
| 关联模板 | 年度模板:`docs/moban/年度教育培训收集模板.xls`(源文件:待办事项1.0.-0825.xlsx,已标准化为内置模板 `internal/assets/trainingtemplates/demand_collection.xlsx` 随二进制分发);月度模板:本期新增 |
|
||||
| 关联代码 | `frontend/src/views/training/`(培训计划 PlanPanel、工作台 WorkbenchPanel/DashboardPanel、课程 CoursePanel、签到 SignPanel)、`internal/handler/training/training.go`(计划域/课程域/签到域)、`internal/application/service/training*.go`、`internal/router/routes_training.go` |
|
||||
| 关联模板 | 年度需求模板:「教育训练需求表模板.xlsx」(2026-11 起系统内置默认,`internal/assets/trainingtemplates/demand_collection.xlsx` 随二进制分发;由 `docs/moban/年度教育培训收集模板.xls` 重制为 xlsx 并增加「计划培训月份」列);题库导入模板:`question_bank.xlsx`;月度排期模板:规划中(未实现,见附录 C) |
|
||||
|
||||
---
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
### 1.1 背景
|
||||
|
||||
公司培训管理涉及人事(培训运营)、部门主管、部门文员、讲师、学员、高管六类角色。年度培训计划需要先向各部门收集需求、汇总排期,再逐月组织课程执行(授课、签到、考试、学习),最后向管理层汇报完成情况并留存佐证用于讲师请款与审计。
|
||||
公司培训管理涉及人事(培训运营)、部门课长/经理、讲师、学员四类核心角色。年度培训计划需要先向各部门收集需求、汇总排期,再逐月组织课程执行(授课、签到、考试、学习),最后向管理层汇报完成情况并留存佐证用于讲师请款与审计。
|
||||
|
||||
随着公司规模扩大、部门增多,培训计划的数据量与协作频次显著上升,原有依赖 Excel / 邮件 / 纸面的手工模式已无法支撑,亟需在 Academy 平台上完成培训计划管理全流程的线上化。
|
||||
|
||||
@@ -25,22 +25,22 @@
|
||||
|
||||
| 环节 | 现状做法 |
|
||||
| --- | --- |
|
||||
| 年度需求收集 | 人事每年 12 月用邮件把「年度教育培训收集模板」(待办事项1.0.-0825.xlsx)发给各部门主管/文员;各部门离线填写后邮件回传 |
|
||||
| 需求汇总排期 | 人事人工汇总各表、逐条核对缺失项(课时/部门/人数),再手工整理成年度排期与月度排期 Excel |
|
||||
| 年度需求收集 | 人事每年年底用邮件把「教育训练需求表模板」(源文件:年度教育培训收集模板)发给各部门课长;各部门离线填写后邮件回传 |
|
||||
| 需求汇总排期 | 人事人工汇总各表、逐条核对缺失项(部门等),再手工整理成年度排期 Excel |
|
||||
| 计划调整 | 需求或排期变动靠邮件/口头沟通,人事在 Excel 中反复改版,版本混乱 |
|
||||
| 月度排课与通知 | 文员按月度排期表手工排课,微信群/电话通知讲师与学员 |
|
||||
| 月度排课与通知 | 按月度安排手工排课,微信群/电话通知讲师与学员 |
|
||||
| 计划执行 | 纸质签到表签到、线下纸质考试;线上学习无统一入口 |
|
||||
| 佐证与请款 | 月底人工汇总签到表、成绩单、培训照片,整理成请款佐证材料 |
|
||||
| 进度查询 | 主管/高管问进度,人事临时人工统计 Excel 回复,无统一看板 |
|
||||
|
||||
### 1.3 问题
|
||||
|
||||
1. **收集慢、易出错**:需求靠邮件收发 Excel,人事需逐表催收、逐行核对;模板格式易被改动,字段缺失(课时、部门、人数)常见,汇总返工多、周期长(典型 2~4 周)。
|
||||
2. **无组织数据约束**:模板中「主办单位」「培训讲师」「参加人员」为自由文本,与组织架构、员工名册脱节,同名错写无法校验,后续排课与名单圈定需二次人工比对。
|
||||
3. **计划与执行两张皮**:年度需求、年度排期、月度排期分散在多个 Excel,需求确认后无法自动流转为课程与排期;计划变更无版本记录,追溯困难。
|
||||
1. **收集慢、易出错**:需求靠邮件收发 Excel,人事需逐表催收、逐行核对;模板格式易被改动,字段缺失(部门)常见,汇总返工多、周期长(典型 2~4 周)。
|
||||
2. **无组织数据约束**:模板中「部门」「讲师」「参加人员」为自由文本,与组织架构、员工名册脱节,同名错写无法校验,后续排课与名单圈定需二次人工比对。
|
||||
3. **计划与执行两张皮**:年度需求与年度排期分散在多个 Excel,需求确认后无法自动流转为课程与场次;计划变更无版本记录,追溯困难。
|
||||
4. **执行过程不透明**:签到、考试、学习数据各自孤立,月度完成率需人工月底统计;未完成课程无人跟踪,容易漏排。
|
||||
5. **查询困难**:「今年整体计划是什么」「要学多少、完成了多少」没有统一口径与视图,管理层每次都要人事临时出数。
|
||||
6. **佐证整理成本高**:请款佐证(签到记录、成绩、照片、视频)靠人工归档拼接,月底集中占用人事/文员大量时间。
|
||||
6. **佐证整理成本高**:请款佐证(签到记录、成绩、照片、视频)靠人工归档拼接,月底集中占用人事大量时间。
|
||||
|
||||
## 2. 需求描述
|
||||
|
||||
@@ -48,24 +48,25 @@
|
||||
|
||||
在 Academy 平台企业培训模块内建设**培训计划管理**能力,实现:
|
||||
|
||||
- **计划在线化**:以「年度教育培训收集模板」为口径,把年度需求收集、汇总排期、月度排期搬到线上,Excel 一次性导入即完成建档;
|
||||
- **计划在线化**:以公司标准「教育训练需求表模板」为口径,把年度需求收集、汇总排期搬到线上,Excel 一次性导入或在线逐条提报即完成建档;
|
||||
- **数据结构化**:部门/讲师/参加人员与组织架构、员工名册强关联(模板下拉由组织数据注入,导入时自动匹配),从源头保证数据质量;
|
||||
- **执行闭环化**:计划确认后自动流转为课程与场次,签到、考试、学习、佐证在系统内完成,未完成自动滚动;
|
||||
- **执行闭环化**:需求确认后自动流转为课程与默认场次(含学员名单),签到、考试、学习、佐证在系统内完成,未完成自动滚动;
|
||||
- **进度可视化**:管理者随时查看整体计划与完成度(要学多少、完成了多少),无需人工统计。
|
||||
|
||||
### 2.2 核心需求清单
|
||||
|
||||
| # | 需求 | 说明 | 优先级 |
|
||||
| # | 需求 | 说明 | 优先级 / 状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 培训计划 Excel 导入(年度模板) | 下载/上传「年度教育培训收集模板」(对应源文件 待办事项1.0.-0825.xlsx,模板字段 1:1 映射),支持模板下载(注入组织架构下拉)、Excel 上传解析、粘贴行快速导入 | P0 |
|
||||
| 2 | 培训计划 Excel 导入(月度模板) | 支持按月下载「月度培训排期模板」并批量导入月度排期,口径与年度模板衔接 | P0(本期新增) |
|
||||
| 3 | 导入后计划维护调整 | 导入结果进入计划列表,支持逐条编辑、删除、批量确认/删除;规则校验缺项并提示;已确认项受保护不可随意改删 | P0 |
|
||||
| 4 | 计划筛选 | 按时间段(年度 + 期望月份)、计划名称(模糊)、部门等条件组合筛选 | P0 |
|
||||
| 5 | 培训计划执行 | 计划确认自动生成草稿课程 → 排期/场次 → 名单圈定 → 签到(防伪+异常复核)→ 考试/线上学习 → 未完成滚动下月 | P0 |
|
||||
| 6 | 查看整体计划 | 年度整体排期视图(各部门、各月计划全景)+ 月度排期明细,支持按角色查看 | P0 |
|
||||
| 7 | 完成度查询 | 课程维度「应学/实学」与学习/考试状态;部门/月度完成率统计;管理层驾驶舱 | P0 |
|
||||
| 8 | 需求收集推送 | 人事一键向各部门主管/文员推送年度需求收集通知(默认勾选、可增删),带模板下载指引 | P1 |
|
||||
| 9 | 导入模板管理 | 配置中心可上传租户自定义模板替换内置默认,可恢复默认;全端生效 | P2 |
|
||||
| 1 | 培训计划 Excel 导入(年度需求模板) | 下载/上传「教育训练需求表模板」,支持模板下载(注入组织架构下拉)、Excel 上传解析、粘贴行快速导入 | P0 · 已实现 |
|
||||
| 2 | 导入后计划维护调整 | 导入/提报结果进入计划列表,支持逐条编辑、删除、批量删除与批量核验;填报/导入统一默认「待核验」;已确认项受保护不可改删 | P0 · 已实现 |
|
||||
| 3 | 计划筛选 | 按年度(需求库实际年份,默认最新一年)、状态、部门、课程名称(模糊)组合筛选;人事查看全部,经理/课长仅本部门数据 | P0 · 已实现 |
|
||||
| 4 | 需求确认流转 | 确认自动生成年度排期行 + 草稿课程 + 默认场次与学员名单 + 讲师自动授权 | P0 · 已实现 |
|
||||
| 5 | 培训计划执行 | 课程发布/排期/场次 → 名单圈定 → 签到(防伪+异常复核+代签)→ 考试/线上学习 → 未完成滚动下月 | P0 · 已实现 |
|
||||
| 6 | 需求收集推送 | 人事一键向各课长推送年度需求收集通知(默认勾选、可增删),站内+企微双通道,带模板下载指引 | P1 · 已实现 |
|
||||
| 7 | 查看整体计划 | 年度整体排期视图(需求收集进度 + 确认汇总生成排期),支持按角色数据范围查看 | P0 · 已实现 |
|
||||
| 8 | 完成度查询 | 课程维度「应学/实学」与学习/考试状态;部门/月度完成率统计;人事/课长/经理三视图驾驶舱 | P0 · 已实现 |
|
||||
| 9 | 导入模板管理 | 配置中心可上传租户自定义模板(需求收集/题库两键)替换内置默认,可恢复默认;全端生效 | P2 · 已实现 |
|
||||
| 10 | 月度排期模板批量导入 | 按月下载「月度培训排期模板」批量导入月度排期 | P0 · **规划中(暂未实现,见附录 C)** |
|
||||
|
||||
## 3. 效益
|
||||
|
||||
@@ -73,8 +74,8 @@
|
||||
|
||||
1. **收集在线化**:需求提报、导入、确认全在一个系统内完成,邮件收发 Excel 退场;
|
||||
2. **数据可信**:部门/讲师/人员与组织架构强关联,缺项自动校验提示,汇总口径统一;
|
||||
3. **计划-执行贯通**:需求确认自动生成课程与排期,杜绝「计划一张表、执行另一张表」;
|
||||
4. **过程可追溯**:计划修改有记录、执行有签到/佐证流水、未完成有滚动与升级提醒;
|
||||
3. **计划-执行贯通**:需求确认自动生成课程、场次与名单,杜绝「计划一张表、执行另一张表」;
|
||||
4. **过程可追溯**:课程修改有版本记录、执行有签到/佐证流水、未完成有滚动与升级;
|
||||
5. **管理自助化**:整体计划与完成率看板随取随用,人事从「人工出数」中解放。
|
||||
|
||||
### 3.2 定量效益(目标值,作为验收口径)
|
||||
@@ -96,145 +97,187 @@
|
||||
|
||||
| 一级场景 | 二级场景 | 三级场景 |
|
||||
| --- | --- | --- |
|
||||
| 1. 培训计划维护 | 1.1 Excel 导入-年度模板 | 下载年度模板(含组织下拉)→ 离线填写 → 上传导入;粘贴行快速导入;解析与自动匹配规则;缺项校验 |
|
||||
| | 1.2 Excel 导入-月度模板(新增) | 下载月度模板 → 填写月度排期 → 上传导入月度排期 |
|
||||
| | 1.3 导入后计划维护调整 | 编辑/删除未确认需求;批量确认/批量删除;确认流转为课程;已确认保护 |
|
||||
| | 1.4 计划筛选 | 按时间段(年度+月份)、计划名称(模糊)、部门、状态组合筛选 |
|
||||
| | 1.5 需求收集推送 | 一键向主管/文员推送收集通知 |
|
||||
| 2. 培训计划执行 | 2.1 排课与场次 | 文员按月度排期排课(线下场次/线上课);讲师与学员通知 |
|
||||
| | 2.2 名单与签到 | 圈定名单;生成签到码(有效期+定位围栏);扫码签到、异常打标、复核、代签 |
|
||||
| | 2.3 考试 | 题库导入、组卷、答题判分、错题本、薄弱点分析 |
|
||||
| | 2.4 线上学习 | 学习任务自动生成、进度上报、逾期提醒 |
|
||||
| | 2.5 未完成滚动 | 月底未完成课程滚动下月置顶,连续两月未完成升级抄送人事 |
|
||||
| 3. 培训计划查询 | 3.1 查看整体计划 | 年度排期总览(部门×月份);月度排期明细 |
|
||||
| | 3.2 完成度查询 | 课程「应到/实到」「学习状态」「考试状态」;月度/部门完成率;三角色驾驶舱 |
|
||||
| 1. 培训计划维护 | 1.1 Excel 导入-年度需求模板 | 下载模板(含组织下拉)→ 离线填写 → 上传导入;粘贴行快速导入;解析与自动匹配规则;缺项校验 |
|
||||
| | 1.2 导入后计划维护调整 | 编辑/删除未确认需求;批量确认/批量删除;确认流转为年度排期 + 课程 + 场次名单;已确认保护 |
|
||||
| | 1.3 计划筛选 | 按年度(选项为需求库实际年份,默认最新一年)、状态、部门、课程名称(模糊)组合筛选;人事全量,经理/课长仅本部门 |
|
||||
| | 1.4 需求收集推送 | 一键向各课长推送收集通知(站内+企微) |
|
||||
| 2. 培训计划执行 | 2.1 排课与场次 | 排课(线下场次/线上课);创建/改期/名单变更自动通知;学员开课通知(立即/T-1) |
|
||||
| | 2.2 名单与签到 | 圈定名单;生成签到码(有效期+定位围栏);扫码签到、异常打标、复核、代签;佐证归档与请款导出 |
|
||||
| | 2.3 考试 | 题库导入、组卷、答题判分、错题本、薄弱点分析、监考代交卷 |
|
||||
| | 2.4 线上学习 | 学习任务自动生成、进度上报、逾期状态 |
|
||||
| | 2.5 未完成滚动 | 未完成课程滚动下月,连续两月未完成升级标记 |
|
||||
| 3. 培训计划查询 | 3.1 查看整体计划 | 年度排期总览 + 需求收集进度;月度排期(后端能力保留) |
|
||||
| | 3.2 完成度查询 | 课程「应到/实到」「学习状态」「考试状态」;人事/课长/经理驾驶舱;个人四宫格 |
|
||||
|
||||
**角色与权限口径**(全模块一致):`hr` 人事·培训运营、`supervisor` 部门主管、`clerk` 部门文员、`lecturer` 讲师、`trainee` 学员(全员默认)、`exec` 高管。空间 RBAC 做粗门槛(学员功能 Viewer+,管理动作 Contributor+),培训模块内再按业务角色细控;不对 API Key 开放。入口:AIDO → 企业培训,子页 `plan` 计划排期 / `course` 课程管理 / `sign` 课堂签到 / `study` 学习考试 / `dashboard` 工作台(数据驾驶舱)。
|
||||
**角色与权限口径**(全模块一致):
|
||||
|
||||
| 角色 key | 名称 | 权限要点 |
|
||||
| --- | --- | --- |
|
||||
| `hr` | 人事(培训运营) | 全部权限:需求导入/确认、排期维护、滚动、模板与规则配置、推送管理 |
|
||||
| `supervisor` | 课长 | 年度培训计划推送/录入、维护课程、查询**本部门**数据(数据范围收窄) |
|
||||
| `exec` | 经理 | 课长全部权限(权限组继承课长)+ 月度排期审批决策 + 管理驾驶舱 + 讲师结算 |
|
||||
| `lecturer` | 讲师 | 只看与自己相关的课程/场次(维护视角),可代签到 |
|
||||
| `trainee` | 学员 | 全员隐式默认角色;工作台课程目录 + 学习考试 |
|
||||
|
||||
- **文员(clerk)角色已移除**:存量成员携带的 clerk 角色经别名映射按课长对待(`LegacyRoleAlias`),平滑过渡。
|
||||
- 角色字典在配置中心可配(`role_dict`),支持自定义职称角色与**权限组继承**(如「资深讲师」继承讲师+课长);权限判定按继承展开后的并集比对(前后端同构)。
|
||||
- 空间 Admin/Owner/SystemAdmin 兜底 bypass(用于冷启动时完成首批人事授权)。
|
||||
- 空间 RBAC 做粗门槛(学员功能 Viewer+,管理动作 Contributor+),handler 内再按职称角色细控;不对 API Key 开放。
|
||||
- 前端入口:AIDO → 企业培训,侧栏子页 `dashboard` 工作台(课程目录 / 个人成长 / 数据驾驶舱三视图切换)/ `plan` 培训计划 / `course` 培训课程 / `sign` 培训签到 / `study` 学习考试 / `members` 职称角色(人事专属)/ `rules` 配置中心(人事专属)。
|
||||
- 页面门槛:培训计划 / 培训课程 / 培训签到三个子页仅**课长/经理/人事/讲师**可见;学员使用工作台与学习考试。
|
||||
|
||||
**主要动作权限矩阵**(后端 `requireRoles` 强校验,空间管理员 bypass):
|
||||
|
||||
| 动作 | 允许角色 |
|
||||
| --- | --- |
|
||||
| 需求批量导入 `demands/import` | hr、课长 |
|
||||
| 需求确认 `demands/:id/confirm` | 经理(exec,本部门口径;其他角色提示「暂无权限核验」) |
|
||||
| 需求编辑/删除 | 提报本人 或 hr/课长(含继承) |
|
||||
| 月度排期新建/编辑 `month-plans` | hr、课长 |
|
||||
| 月度排期审批 `month-plans/:id/approve` | 经理(exec)、hr |
|
||||
| 月度滚动 `month-plans/roll` | hr |
|
||||
| 需求收集推送 `notifications/broadcast` | hr、课长 |
|
||||
| 数据范围 | 人事/空间管理员在需求/年度排期/月度排期/收集进度列表查看**全部**数据;经理/课长(含继承课长的自定义角色)仅见**本部门**数据;核验确认=**仅经理**(其他角色提示「暂无权限核验」,且仅可核验本部门需求) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 一级场景:培训计划维护
|
||||
|
||||
入口:企业培训 → 计划排期(`PlanPanel`),页面主体为「年度需求收集(年度)」列表,支持年度切换(近 4 年 + 明年)。
|
||||
入口:企业培训 → 培训计划(`PlanPanel`),页面主体为「年度需求收集」列表,标题旁内嵌年度切换(选项为需求库实际年份去重列表,降序,默认选中最新一年并展示该年数据;无数据时回退当前年度;切换即刷新)。页面操作按钮按角色显示:「收集下年度计划」「批量导入」仅人事/课长可见;「在线提报需求」对可进入本页的所有角色可见(学员无本页入口)。
|
||||
|
||||
### 1.1 二级场景:支持 Excel 导入 —— 年度模板
|
||||
### 1.1 二级场景:支持 Excel 导入 —— 年度需求模板
|
||||
|
||||
**三级场景 1:下载模板(含组织架构下拉)**
|
||||
|
||||
1. 用户点击「批量导入」→「下载年度教育培训收集模板」;
|
||||
2. 前端请求 `GET /api/v1/training/templates/demand_collection/file`,后端返回**生效模板**:租户在配置中心上传的自定义版本优先(存 `tr_templates`),未上传或已「恢复默认」时回退二进制内置文件(源自 `docs/moban/年度教育培训收集模板.xls`,即源文件「待办事项1.0.-0825.xlsx」的标准化版本);
|
||||
1. 用户在「批量导入」弹窗点击「下载教育训练需求表模板」;
|
||||
2. 前端请求 `GET /api/v1/training/templates/demand_collection/file`,后端返回**生效模板**:租户在配置中心上传的自定义版本优先(存 `tr_templates`),未上传或已「恢复默认」时回退二进制内置文件(`demand_collection.xlsx`,即 2026-11 起的公司标准「教育训练需求表模板.xlsx」);
|
||||
3. 后端下载时对模板动态注入组织数据(`enrichDemandTemplate`):
|
||||
- 表头「主办单位」改写为「部门单位」,下拉取值 = 组织架构部门(`org_depts`);
|
||||
- 「参加人员」「培训讲师」下拉取值 = 员工档案人员(`users.username` 联查去重,上限 2000 人);
|
||||
- 取值写入工作表右侧隐藏辅助列 CA/CB/CC,以数据验证下拉挂到「部门单位 / 参加人员 / 培训讲师」列,覆盖第 4~503 数据行;
|
||||
- 「部门」(B 列)下拉 = 组织架构部门(`org_depts`);
|
||||
- 「参加人员」(D 列)「讲师」(I 列)下拉 = 员工档案人员姓名(display_name 真实姓名优先、回退 username 工号;去重去空,上限 2000 人);
|
||||
- 取值写入工作表右侧隐藏辅助列 CA/CB/CC,以数据验证下拉挂到对应列,覆盖第 4~503 数据行;
|
||||
- 下拉为**非阻断式**:单元格可自由填写——参加人员可填多人(、/,分隔),讲师可填系统外姓名;选中单元格浮出输入提示引导填写方式;
|
||||
- 模板不可解析(如旧 .xls 自定义版)或组织数据拉取失败时原样返回,不阻断下载。
|
||||
|
||||
**三级场景 2:离线填写模板**
|
||||
|
||||
模板列口径(与人事现有模板 1:1 映射):`厂区 / 部门单位(原主办单位) / 课程名称 / 次数 / 参加人员 / 地点 / 分类 / 培训讲师 / 培训时间 / 月份`。前两行为公司名/表题合并单元格,自「课程名称」表头行起为数据行;部门与讲师通过下拉选择保证与名册一致。
|
||||
模板列口径(公司标准「教育训练需求表模板」1:1 映射):`编号 / 部门 / 课程名称 / 参加人员 / 地点 / 培訓費用 / 內外培訓(内部或外部) / 计划培训月份 / 讲师 / 备注`。前两行为公司名/表题合并单元格,自「课程名称」表头行起为数据行。下载时由后端动态注入:标题年份=**下一年度**(如 2026 年下载即为「2027 年度教育训练需求表」);下拉列——课程名称 C(课程管理名称)/ 计划培训月份 H(1~12)/ 部门 B(组织架构)/ 讲师 I(员工档案);「参加人员」D 列**不挂下拉**(自由填写多人)。
|
||||
|
||||
**三级场景 3:上传导入**
|
||||
|
||||
1. 用户选择填写好的 .xlsx/.xls 上传(前端 `xlsx` 库解析):
|
||||
- 遍历工作表,定位含「课程名称」表头的行作为表头行,其后为数据行;
|
||||
- 未找到「课程名称」表头 → 报错「请使用下载的年度教育培训收集模板填写」;
|
||||
2. 逐行自动匹配(前端完成,结果提交 `POST /training/demands/import`):
|
||||
- **讲师匹配**:按「培训讲师」姓名精确匹配讲师名册;未命中 → 讲师置空,备注写入「讲师待分配:×××」,待人事务分配;
|
||||
- **部门匹配**:按「部门单位」(新版表头)/「主办单位」(旧版表头)匹配组织架构,支持名称包含匹配;未命中 → 留空,导入后进入「待校验」由人事确认补全;
|
||||
- **月份解析**:优先取「月份」列;缺失时回退解析「培训时间」(支持 `2026/6/8`、`6月8日` 等格式);均无则默认 1 月;
|
||||
3. 行级容错:未填课程名称的行跳过并在导入结果中提示「另有 N 行未填课程名称已跳过」;
|
||||
4. 导入成功 → 列表刷新,显示「已从模板导入 N 条需求」。
|
||||
- 遍历工作表,定位含「课程名称」表头的行作为表头行,其后为数据行;表头键做空白归一(兼容「地 点」等内含空格的列名);
|
||||
- 未找到「课程名称」表头 → 报错「未找到『课程名称』表头,请使用下载的教育训练需求表模板填写」;
|
||||
2. 逐行自动匹配(前端完成,结果提交 `POST /training/demands/import`,接口仅人事/课长可调):
|
||||
- **部门匹配**:取「部门单位」(收集模板)、「主办单位」(旧版)或「部门」(需求表模板)列,先按部门名精确匹配组织架构、未命中再按名称包含匹配;未命中 → 留空,导入后进入「待校验」由人事确认补全;
|
||||
- **讲师匹配**:取「培训讲师」或「讲师」列,按**全部在职员工**姓名精确匹配(不限于讲师名册):命中 → 绑定 `lecturer_id`,且该行部门未匹配时**自动带出讲师所在部门**;未命中 → 作为**外部讲师姓名**落 `lecturer_external`,列表讲师列照常显示;
|
||||
- **计划培训月份解析**:新「计划培训月份」列(下拉 1~12)优先,兼容旧「计划培训时间」列;接受纯月份(`1`、`12月`)与旧日期格式(`2027-1`、`2026/6/8`、`2026年6月8日` 等取其月份);年份统一取收集年度(模板标题年),入库 `planned_time=YYYY-M`(如 `2027-1`)并回填期望月份 `expect_month`,解析失败留空;
|
||||
- 行级容错:未填课程名称的行跳过,导入结果提示「另有 N 行未填课程名称已跳过」;
|
||||
3. 导入成功 → 列表刷新,提示「已从模板导入 N 条需求」及讲师匹配/外部讲师/部门按讲师带出/跳过行的汇总明细。
|
||||
|
||||
**三级场景 4:粘贴行快速导入**
|
||||
|
||||
在导入弹窗文本框按 `课程名称,期望月份,人数,课时` 粘贴多行(兼容中英文逗号与制表符),缺课程名称的行跳过并提示行号;适用于零散补录。
|
||||
在导入弹窗文本框按 `课程名称[,计划培训月份如 3]` 粘贴多行(兼容中英文逗号与制表符),缺课程名称的行跳过并提示行号;适用于零散补录。
|
||||
|
||||
**导入校验规则(与在线提报同口径,服务端执行)**:
|
||||
**三级场景 5:在线提报**
|
||||
|
||||
「在线提报需求」弹窗表单:课程名称(必填)/ 所属部门(只读展示,提交时按提报人所在部门自动获取;编辑时回显原部门)/ 参加人员(选填,多人用、/,分隔)/ 计划培训月份(下拉 1~12 月,选填,只需选到月份;提交时与收集年度合成 `YYYY-M` 入库并回填期望月份)/ 内外培训(未选择/内部/外部)/ 厂区 / 地点 / 培训次数(默认 1)/ 讲师(下拉可选讲师名册,支持直接输入外部讲师姓名)/ 备注。讲师提交时解析:名册 id 直接用 → 名册姓名映射为 id → 其余落外部姓名。
|
||||
|
||||
**导入校验规则(服务端执行,与在线提报同口径)**:
|
||||
|
||||
| 校验项 | 结果 |
|
||||
| --- | --- |
|
||||
| 课时未填写 / 未指定部门 / 未填培训人数 | `check_status=pending`,`check_msg` 逐条列出缺项(如「课时未填写;未填培训人数」),列表标「待校验」 |
|
||||
| 三项齐全 | `check_status=passed` |
|
||||
| 未指定部门 | `check_status=pending`,`check_msg=「未指定部门」`,列表标「待核验」 |
|
||||
| 部门齐全 | `check_status=pending`(校验提示仅作补全参考,不自动通过) |
|
||||
| 年份缺省 | 取当前年度 |
|
||||
|
||||
### 1.2 二级场景:支持 Excel 导入 —— 月度模板(本期新增)
|
||||
> 口径说明:自模板对齐公司标准「教育训练需求表模板」后,人数/课时不再采集,规则校验仅针对部门;填报/导入**统一默认「待核验」**,由经理核验确认后才置「已确认」;「计划培训月份」与收集年度合成入库(见 1.1 计划培训月份解析)。
|
||||
|
||||
**三级场景 1:下载月度模板**:计划排期页新增「下载月度培训排期模板」入口;模板按月组织,列口径与年度模板衔接并增加执行字段:`月份 / 部门单位 / 课程名称 / 计划日期时间 / 地点 / 讲师 / 参加人员(名单) / 课时`;模板管理沿用配置中心机制(自定义版优先、内置默认兜底)。
|
||||
### 1.2 二级场景:导入后计划维护调整
|
||||
|
||||
**三级场景 2:上传导入月度排期**:解析规则与年度模板一致(定位表头 → 行映射 → 部门/讲师按名册匹配);每行生成一条月度排期(`tr_month_plans`,状态 `draft`),落库后进入月度排期列表走既有审批链路(见 2.1);缺课程名称行跳过,部门未匹配进入待补全提示。
|
||||
|
||||
**三级场景 3:与年度计划衔接**:月度排期可关联年度计划(`annual_plan_id`),看板与整体计划视图按关联关系聚合「年度计划 → 月度排期 → 执行结果」。
|
||||
|
||||
### 1.3 二级场景:导入后计划维护调整
|
||||
|
||||
**三级场景 1:编辑未确认计划**:列表行点击「编辑」打开表单(课程名称/分类/期望月份/次数/人数/课时/厂区/地点/适用岗位/讲师/备注),保存走 `POST /training/demands`;编辑权限:提报本人或 hr/clerk/supervisor;**已确认需求不可编辑**(先由人事回退)。新建时部门按提报人所在部门自动获取。
|
||||
**三级场景 1:编辑未确认计划**:列表行点击「编辑」打开提报表单复用编辑;保存走 `POST /training/demands`。编辑权限:提报本人或 hr/课长(含继承)或空间管理员;**已确认需求不可编辑**(先由人事回退)。编辑未显式指定部门时保留原部门。
|
||||
|
||||
**三级场景 2:删除未确认计划**:行内「删除」带二次确认;**已确认需求不可删除**(保护已纳入年度排期的口径)。
|
||||
|
||||
**三级场景 3:批量确认**:勾选多条未确认需求 →「批量确认」(已确认行禁止勾选);逐条调用 `POST /training/demands/:id/confirm`,结果汇总提示成功/失败条数;确认动作(`ConfirmDemand`):
|
||||
1. 按「来源需求」判重生成年度排期行(`tr_annual_plans`,计划月份=期望月份,状态 `planned`),不重复生成;
|
||||
2. 需求状态置 `confirmed`、校验状态置 `passed`(先落排期再改状态,排期失败则一并失败);
|
||||
3. 自动同步生成**草稿课程**到课程管理(同名课程已存在则跳过;线下/必修;课时、讲师、部门、岗位、授课时间=期望月份 `YYYY-MM` 随需求带入)。
|
||||
**三级场景 3:核验确认(单条 + 批量)**:未确认行对**经理**角色显示「确认」(批量确认按钮同权限;其他角色不可见,直接调接口统一提示「暂无权限核验」);经理仅可核验**本部门**需求(部门缺失的需求先由人事补全部门)。批量确认勾选多条(已确认行禁止勾选)后逐条调用 `POST /training/demands/:id/confirm`,汇总提示成功/失败条数。确认动作链路:
|
||||
|
||||
1. **生成年度排期行**(`tr_annual_plans`,年份=需求年份、部门/课程随需求、计划月份=期望月份(<1 取 1)、状态 `planned`),按「来源需求」判重,不重复生成;
|
||||
2. **状态回写**:需求状态置 `confirmed`、校验状态置 `passed`(先落排期再改状态,排期失败则确认一并失败,避免「已确认但无排期」);
|
||||
3. **自动同步草稿课程**到课程管理(`syncDemandCourse`,fail-open 不阻断确认):
|
||||
- 同名课程已存在则跳过(避免重复确认重复建课);
|
||||
- 课程形式线下 `offline`、类型必修 `required`;课时/讲师/适用部门/适用岗位随需求带入,授课时间 `teach_time` = 期望月份 `YYYY-MM`;「计划培训月份」`planned_time` 需求侧为 `YYYY-M`,同步课程时归一为 `YYYY-MM`(旧日期格式原样同步);
|
||||
- 需求录入信息全量同步:内/外培训、厂区、地点、培训次数、备注、分类(写入课程标签);外部讲师仅无系统讲师时生效;课程详情弹窗只读回显;
|
||||
4. **生成默认场次与学员名单**(`syncDemandParticipants`):参加人员按姓名拆分(、/,/分号/空格分隔)→ 按员工档案姓名匹配在职员工 → 为新课程建默认场次(通知方式 `immediate`;计划培训时间可解析到日时取为开课时间,月份精度留空,结束时间=开课+课时)→ 批量写入名单(自动去重)→ 名单学员收到开课通知;未匹配到的姓名(外部人员/笔误)跳过;跨场次名单去重即课程「应到人数」来源;
|
||||
5. **讲师自动授权**(`EnsureLecturerRole`):需求选定讲师(可能是任意员工)自动补齐培训模块 lecturer 角色绑定,已有则幂等跳过,档案缺失 fail-open。
|
||||
|
||||
**三级场景 4:批量删除**:勾选多条未确认需求 →「批量删除」,逐条软删,汇总成功/失败条数。
|
||||
|
||||
### 1.4 二级场景:计划筛选
|
||||
### 1.3 二级场景:计划筛选
|
||||
|
||||
**三级场景**:列表上方筛选区,条件全部在后端过滤(`GET /training/demands`):
|
||||
列表上方筛选区,条件全部在后端过滤(`GET /training/demands`):
|
||||
|
||||
| 筛选维度 | 形态 | 参数 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 时间段-年度 | 年度下拉(近 4 年+明年) | `year` | 标题内嵌切换,切换即刷新 |
|
||||
| 时间段-月份 | 期望月份下拉(1~12月) | `month` | 对应「期望月份」字段 |
|
||||
| 部门 | 部门下拉(可搜索) | `dept_id` | 数据源组织架构部门树 |
|
||||
| 时间段-年度 | 年度下拉(需求库实际年份去重,降序) | `year` | 数据源 `GET /training/demands/years`,默认选中最新一年;标题旁切换,切换即刷新 |
|
||||
| 部门 | 部门下拉(可搜索) | `dept_id` | 数据源组织架构部门树;经理/课长被服务端强制收窄为本部门 |
|
||||
| 计划名称 | 文本输入 | `keyword` | 课程名称模糊搜索,回车触发 |
|
||||
| 状态 | 下拉 | `confirmed`→`status`;待校验/已修正→`check_status` | 已确认按人工状态过滤,其余按规则校验状态过滤 |
|
||||
| 状态 | 下拉(待核验/已确认/已修正) | `confirmed`→`status`;待核验/已修正→`check_status` | 已确认按人工确认状态过滤,其余按规则校验状态过滤 |
|
||||
|
||||
支持「查询 / 重置」;筛选条件与批量确认/删除按钮同行。
|
||||
支持「查询 / 重置」;筛选条件与批量确认(仅经理)/批量删除按钮同行;列表固定返回 100 条。状态列展示规则校验状态:已确认(绿,=经理核验通过)/ 待核验(黄,=填报/导入默认态)/ 已修正(灰);已确认行整行文字保持正常色(仅禁止勾选);操作列对未确认行提供 确认(仅经理)/编辑/删除(状态/操作列固定右侧,横向滚动始终可见)。
|
||||
|
||||
### 1.5 二级场景:需求收集推送
|
||||
### 1.4 二级场景:需求收集推送
|
||||
|
||||
**三级场景**:hr/clerk 点击「收集下年度计划」→ 弹窗展示模板下载入口 + 推送人员(默认勾选各部门主管 `supervisor` 与文员 `clerk`,可增删,数据源员工名册)+ 通知内容(预置文案与截止日期)→「确认推送」经 `POST /training/notifications/broadcast` 批量发站内通知(场景 `demand_collect`),收件人从通知栏可直达提报页面。
|
||||
**三级场景**:hr/课长点击「收集下年度计划」→ 弹窗(标题带次年年份):
|
||||
|
||||
1. **发送模板**:展示「教育训练需求表模板」下载入口与填写指引(填写后经「批量导入」上传,或「在线提报需求」逐条填写);
|
||||
2. **发送人员**:员工名册多选,默认勾选**各课长**(存量文员经别名按课长对待),可增删;
|
||||
3. **通知内容**:预置文案(含截止日期:次年 1 月 31 日前完成提报);
|
||||
4. 「确认推送」经 `POST /training/notifications/broadcast` 批量推送,场景 `demand_collect`、引用 `plan/次年`;**站内 + 企业微信双通道**(未绑定企微的同事仅站内送达),推送逐人明细可在配置中心「推送记录」查看;收件人从通知栏可直达提报页面。
|
||||
|
||||
---
|
||||
|
||||
## 2. 一级场景:培训计划执行
|
||||
|
||||
计划确认生成课程后,进入「课程管理(CoursePanel)→ 课堂签到 → 学习考试」执行链路。
|
||||
计划确认生成课程与默认场次后,进入「培训课程(CoursePanel)→ 培训签到(SignPanel)→ 学习考试(StudyPanel)」执行链路。
|
||||
|
||||
### 2.1 二级场景:排课与场次
|
||||
|
||||
- **课程**:状态 `draft/published`;形式线下 `offline` / 线上 `online`;类型必修/选修;创建为 5 步合一表单(类型/名称/讲师/时间地点/学员范围),可关联题库(绑定即具备在线考试条件);每次保存生成字段级变更版本记录(`GET /courses/:id/change-logs`);
|
||||
- **课程**:状态 `draft/published`;形式线下 `offline` / 线上 `online`;类型必修/选修;创建为合一表单(类型/名称/学时学分/讲师/时间地点/适用部门/参加人员/课件/题库),可关联题库(绑定即具备在线考试条件);每次保存生成字段级变更版本记录(`GET /courses/:id/change-logs`,涵盖名称/形式/类型/学时/学分/讲师/适用部门/岗位/授课时间/计划培训时间/简介);
|
||||
- **发布前置校验**:线上课必须已登记课件资料,线下课必须已指定讲师;
|
||||
- **线上课发布**:按课程部门范围对在职成员批量生成学习任务(期限默认 7 天,提醒 every_3_days),并通知讲师;
|
||||
- **场次(session)**:一次排课的执行实例,状态 `scheduled/ongoing/finished/cancelled`;文员经 `POST /training/sessions` 排课(时间/地点/容量/讲师),创建与改期自动通知讲师与名单学员;线下课可关联月度排期(改期同步排期时间);
|
||||
- **名单**:`PUT /sessions/:id/enrollments` 整表替换报名名单(自动去重);文员可回填完成/缺席及原因。
|
||||
- **线上课发布**:按课程部门范围(未设范围则全员)对在职成员批量生成学习任务(期限默认 7 天,可配 `learning_policy.default_days`;提醒 `every_3_days`)并逐个通知;同时通知讲师课程已发布;
|
||||
- **数据范围**:课程列表全局视角(人事/课长/经理/空间管理员)按参数过滤;学员目录视图只看已发布课程;纯讲师仅自己讲师相关课程(含草稿,供维护);课程详情对纯学员隐藏未发布课程;
|
||||
- **场次(session)**:一次排课的执行实例,状态 `scheduled/ongoing/finished/cancelled`;排课(时间/地点/容量/讲师/线上 URL);创建自动通知讲师与名单学员(「开课通知」);改期自动通知讲师;
|
||||
- **学员开课通知方式**(`notify_mode`):`immediate`(默认,名单就绪立即推)/ `day_before`(调度器开课前一天推);课件就绪后自动补推未通知学员(课件门控 + 场景幂等,新加学员补发、重复保存不重发);人事/讲师可对场次手动「立即推送学员」(`POST /sessions/:id/notify`);
|
||||
- **场次 ↔ 月度排期联动**:场次可关联月度排期(`month_plan_id`),改期自动同步排期开始时间(fail-open);
|
||||
- **名单**:`PUT /sessions/:id/enrollments` 整表替换报名名单(自动去重,变更逐个通知学员);培训管理角色可回填完成/缺席及原因(`POST /enrollments/:id/result`)。
|
||||
|
||||
### 2.2 二级场景:名单与签到
|
||||
|
||||
- **签到码**:文员为场次生成签到码(32 位短码;有效期默认开课 + 4 小时,已开课则 now + 12 小时;可带定位围栏,默认半径 300m);
|
||||
- **签到**:学员扫码签到,规则引擎确定性打标(不调 LLM):
|
||||
- **签到码**:为场次生成签到码(32 位短码 token;有效期 = 开课 + 4 小时,开课时间未设或已过则 now + 12 小时;可带定位围栏,半径默认 300m,可配 `sign_policy.geo_radius_m`);
|
||||
- **签到**(`POST /sign-records/checkin`)规则引擎确定性打标(不调 LLM),异常标记叠加于 `abnormal_flags`,状态取最后命中项(名单外 > 定位外 > 迟到):
|
||||
|
||||
| 异常 | 判定 | 处理 |
|
||||
| --- | --- | --- |
|
||||
| 迟到 `late` | 晚于开课 + 15 分钟(`sign_policy.late_after_min`) | 标记,可复核 |
|
||||
| 定位外 `outside` | 距签到点超半径 | 标记,可复核 |
|
||||
| 名单外 `not_in_roster` | 不在报名名册 | 状态 `abnormal`,进入待复核队列并通知 |
|
||||
| 代签 `proxy` | 同一入口传 `member_id` 补录/代扫 | 完整走防伪规则,`proxy` 标记留痕 |
|
||||
| 重复扫码 | 唯一约束 | 拒绝 |
|
||||
- **复核**:hr/clerk/supervisor 对异常记录确认(置 `normal`)或驳回;
|
||||
- **佐证**:场次可上传签到照(单张 ≤50MB)与培训视频(≤200MB),对象存储留存、支持在线预览;「一键导出请款佐证包」Excel(部门/工号/姓名/签到时间/讲师/课程/上课时间/成绩 8 列)。
|
||||
| 定位外 `outside` | 距签到点超半径(haversine 距离) | 标记,可复核 |
|
||||
| 名单外 `not_in_roster` | 不在报名名册 | 状态 `abnormal`,进入待复核队列并通知本人 |
|
||||
| 代签 `proxy` | 同一入口传 `member_id` 补录/代扫(限讲师/课长/人事) | 以目标成员身份完整走防伪规则,`proxy` 标记留痕 |
|
||||
| 重复扫码 | 唯一约束 | 直接拒绝 |
|
||||
- 另有前置拦截:签到码无效/过期、场次已取消或已完结、未建立培训档案 → 拒绝签到;
|
||||
- **复核**:hr/课长等管理角色对异常记录确认(置 `normal`)或驳回(保持 `abnormal`),记录复核人与时间;
|
||||
- **佐证**:场次可上传签到照(`sign_photo`,走平台默认文件大小上限)与培训视频(`training_video`,≤200MB),原始文件留存、支持在线预览与删除;
|
||||
- **请款佐证**:「一键导出请款佐证包」Excel(`POST /evidence/export`),8 列:部门 / 工号 / 姓名 / 签到时间 / 讲师姓名 / 课程名称 / 上课时间 / 学员考试成绩。
|
||||
|
||||
### 2.3 二级场景:考试
|
||||
|
||||
题库 Excel 导入(单选/多选/判断三工作表模板,缺答案题跳过;原始文件同步进「企业培训(题库)」知识库)→ 确定性组卷(难度分层 3:5:2,默认 20 题,满分 100 按题均摊,及格线默认 75 可配,支持 A/B 卷)→ 学员答题客观题即时判分 → 通过后锁定不可重考、未通过可覆盖重考取最新成绩;达标自动置该场次报名为「完成」;错题写入个人+部门错题本,按知识点聚合班级薄弱点。
|
||||
题库 Excel 导入(单选/多选/判断三工作表模板,缺答案题跳过;原始文件同步进「企业培训(题库)」知识库,亦支持从知识库文档解析建题库与 AI 课件生成试题)→ 确定性组卷(难度分层简单/中等/困难 = 3:5:2,默认 20 题,满分 100 按题均摊,支持一键 A/B 卷;线上自学卷独立版本号)→ 学员答题客观题即时判分(学员视图剥离答案与解析,讲师/课长/人事可见完整数据)→ 及格线取配置 `pass_line.default`(种子默认 75,未配置回退 60)→ 通过后锁定不可重考、未通过可覆盖重考取最新成绩;成绩达标自动置该场次报名为「完成」;支持监考代交卷(`exam-records/submit-for`,讲师/课长/人事为线下答题学员录入答卷);错题写入个人错题本(记录部门与知识点维度),考试分析按知识点聚合**部门薄弱点**与错误率(`GET /exams/:session_id/analysis`)。
|
||||
|
||||
### 2.4 二级场景:线上学习
|
||||
|
||||
学员在课程详情页学习课件:视频每 15 秒、文档每 30 秒按停留档位上报进度(取历史最大值防回退);**进度 ≥95% 自动完成任务**并发自学积分(默认 3 分);任务状态 `pending/doing/done/overdue`,按 `remind_policy`(T-3/T-1/第三周/月底)催办。
|
||||
学员在课程详情页学习课件:视频每 15 秒按播放位置、文档每 30 秒按停留档位(30→60→95)上报进度(取历史最大值防回退);**进度 ≥95% 自动完成任务**并发自学积分(`point_rules.self_study`,默认 3 分);任务状态 `pending/doing/done/overdue`;学习任务催办策略(`remind_policy`:T-3/T-1/第三周/月底)为配置中心可配项。积分规则种子:必修完成 10 / 成绩≥90 追加 10 / 成绩满分追加 20 / 考试通过 5 / 选修完成 5 / 自学完成 3。
|
||||
|
||||
### 2.5 二级场景:未完成滚动
|
||||
|
||||
hr/clerk 在月底触发 `POST /training/month-plans/roll`:汇总该月未完成的报名所涉场次,逐一生成**下月排期(置顶、状态 draft、`roll_from_id` 溯源)**;同月同名幂等跳过;`roll_times ≥ 2`(连续两月未完成)自动置 `escalated` 升级并抄送人事(`roll_policy.escalate_after`)。
|
||||
hr 触发 `POST /training/month-plans/roll`(月份跨年自动进位):汇总该月未完成的报名所涉场次,逐一生成**下月月度排期**(状态 `draft`、`roll_from_id` 溯源**未完成场次 ID**、`roll_times` 沿关联排期累加);同月同名幂等跳过;`roll_times ≥ 2`(连续两月未完成)自动置 `escalated` 升级标记(`roll_policy.escalate_after` 可配,默认 2)。新排期在列表中按创建时间倒序自然靠前展示(无独立置顶字段);`rolled` 状态常量保留但当前未实际使用。
|
||||
|
||||
---
|
||||
|
||||
@@ -245,61 +288,130 @@ hr/clerk 在月底触发 `POST /training/month-plans/roll`:汇总该月未完
|
||||
**三级场景 1:年度整体排期视图**
|
||||
|
||||
- 数据源 `GET /training/annual-plans?year=`(`tr_annual_plans`:年度 × 部门 × 课程 × 课时 × 计划月份 × 来源需求 × 状态)+ `GET /training/annual-plans/progress`(各部门需求收集进度 done/total/percent);
|
||||
- 展示:按「部门 × 计划月份」矩阵呈现全年计划全景,每行可追溯到来源需求与对应课程/场次执行状态;作为「整体计划」的权威口径,人事确认需求与「汇总生成年度排期」(`POST /annual-plans/generate`,按来源需求判重)双通道维护;
|
||||
- 权限:全员可读列表(Viewer+),生成/确认为 hr。
|
||||
- 展示:全年计划全景,每行可追溯到来源需求与对应课程/场次执行状态;作为「整体计划」的权威口径,经理核验需求与「汇总生成年度排期」(`POST /annual-plans/generate`,按来源需求判重,仅 hr)双通道维护;
|
||||
- 权限:全员可读列表(Viewer+);**经理/课长仅见本部门**排期与进度行(人事全量);
|
||||
- 前端口径:培训计划子页以「年度需求收集」列表为主视图;年度排期/收集进度由驾驶舱(人事视图)呈现部门收集进度条。
|
||||
|
||||
**三级场景 2:月度排期明细**
|
||||
**三级场景 2:月度排期(后端能力保留)**
|
||||
|
||||
- 数据源 `GET /training/month-plans`(支持 year/month/dept_id/status 过滤);
|
||||
- 展示:当月排期列表(标题/部门/时间/地点/讲师/状态/滚动来源与次数),主管可审批(通过/调整/驳回并填写原因),文员可排课与滚动;
|
||||
- 状态机:`draft → submitted → approved / rejected(含原因) → rolled(滚动置顶)`。
|
||||
- 数据源 `GET /training/month-plans`(支持 year/month/dept_id/status 过滤,经理/课长强制本部门);月度排期仍承担:部门看板的「本月部门排期/待审批」指标来源、场次关联联动(改期同步排期时间)、未完成滚动载体;
|
||||
- 状态机:`draft → submitted → approved / rejected(含原因)`;审批动作 `pass / adjust / reject`(经理+人事,`draft/submitted` 状态可审批);
|
||||
- 前端现状:计划子页已无月度排期管理区块(API 封装保留于 `frontend/src/api/training`,暂无组件消费);手工排课以课程场次为准。月度排期模板批量导入为**规划中**能力(见附录 C)。
|
||||
|
||||
### 3.2 二级场景:看要学多少、完成了多少
|
||||
|
||||
**三级场景 1:课程维度完成度(课程管理列表)**
|
||||
**三级场景 1:课程维度完成度(培训课程列表)**
|
||||
|
||||
- 「应到/实到」:应到 = 各场次名单去重成员数;实到 = 各场次签到 ∪ 已开始线上学习的去重成员数;
|
||||
- 「学习状态」:无参与 → 未学习;完成人数(签到 ∪ 任务 done)≥ max(应到, 参与) → 已学习;否则学习中;线下课签到即视同完成;
|
||||
- 「应到/实到」:应到 = 各场次名单去重成员数;实到 = 各场次签到 ∪ 已开始线上学习的去重成员数;另展示上报部门(课程创建人所属部门);
|
||||
- 「学习状态」:无人签到且无人开始学习 → 未学习;完成人数(签到 ∪ 任务 done)≥ max(应到, 参与) → 已学习;否则学习中;线下课签到即视同完成;
|
||||
- 「考试状态」:无考试记录 → 未考试;已考人数 ≥ max(应到, 已考名单) → 已考试;否则考试中;
|
||||
- 状态标签可点击直达「课程学习情况 / 课程考试情况」逐人明细(工号/岗位/部门/任务状态/成绩)。
|
||||
|
||||
**三级场景 2:管理驾驶舱(`GET /training/dashboards/hr|department|exec`)**
|
||||
**三级场景 2:管理驾驶舱(工作台 dashboard 子页 · 数据驾驶舱视图,`GET /training/dashboards/hr|department|exec`)**
|
||||
|
||||
| 视图 | 角色 | 指标 |
|
||||
| 视图 | 可见角色 | 指标 |
|
||||
| --- | --- | --- |
|
||||
| HR 视图 | hr/clerk | 年度需求收集(部门数)、年度课程总数(线上/线下拆分)、**本月完成率**(已完成/总数,≥90% 绿 / <70% 红)、本月排期场次;年度需求收集进度(按部门进度条);人事待办(待确认需求) |
|
||||
| 部门视图 | supervisor | 本月部门排期、待审批数、部门完成率、未完成预警人次 |
|
||||
| 高管驾驶舱 | exec | 月度达成率、累计积分发放、活跃讲师数;部门培训达成率年度排名;讲师积分榜 TOP5(可月度结算);AI 月度盘点摘要 |
|
||||
| 人事视图 | hr | 年度需求收集(部门数)、年度课程总数(已发布,线上/线下拆分)、**本月完成率**(已完成/总数,≥90% 绿 / 70~90% 默认 / <70% 红)、本月排期场次;年度需求收集进度(按部门进度条);人事待办(待确认需求,前 8 条) |
|
||||
| 部门视图 | 课长(经理经继承同样可见) | 本月部门排期、待审批数、部门完成率、未完成预警人次、本月场次 |
|
||||
| 管理驾驶舱 | 经理(exec) | 月度达成率、累计积分发放、活跃讲师数;部门培训达成率年度排名;讲师积分榜 TOP5(人事可「结算本月」:按时开课 40% + 学员评分 50% + 互动答疑 10%,权重可配 `lecturer_score_weight`);AI 月度盘点摘要(规则引擎版,LLM 摘要由后续调度器接通) |
|
||||
|
||||
**三级场景 3:个人完成度(学习考试页)**
|
||||
|
||||
学员四宫格:学习任务(待学习/学习中/已完成/已逾期)、考试成绩、错题本、能力画像(岗位胜任度 vs 达标线、累计积分、平均成绩、学习时长、课程数)——回答「我要学多少、完成了多少」。
|
||||
学员四宫格:我的学习任务(待学习/学习中/已完成/已逾期,进度 ≥95% 自动完成)、我的考试成绩、我的错题本、我的能力画像(岗位胜任度 vs 达标线、累计积分、平均成绩、学习时长、课程数)——回答「我要学多少、完成了多少」;另有「课程学习情况 / 课程考试情况 / AI 课程分析」管理侧分区。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:核心数据模型(`tr_*` 表,均含 tenant_id)
|
||||
## 附录 A:核心数据模型
|
||||
|
||||
培训域 `tr_*` 表均含 `tenant_id`;部门/员工档案已提升为**租户级共享组织中心**(迁移 000137):`org_depts` / `org_employees`,培训职称角色绑定于 `org_module_members`(`module_key='training'`),`tr_members` / `tr_depts` 为兼容别名。
|
||||
|
||||
| 表 | 说明 |
|
||||
| --- | --- |
|
||||
| `tr_demands` | 年度需求提报(厂区/部门/课程/次数/参加人员/地点/分类/讲师/期望月份/课时/人数;check_status+check_msg 校验回执;status submitted/confirmed) |
|
||||
| `tr_demands` | 年度需求提报(年份/部门/提报人/课程名称/厂区/分类/培训次数/参加人员 post_scope/地点/讲师 id/外部讲师姓名/内外培训/人数/课时/期望月份/计划培训时间/备注;check_status+check_msg 校验回执;status submitted/confirmed) |
|
||||
| `tr_annual_plans` | 年度汇总排期(year/dept/课程/课时/计划月份/source_demand_id 判重溯源/status planned) |
|
||||
| `tr_month_plans` | 月度排期(审批载体;draft/submitted/approved/rejected/rolled;roll_from_id/roll_times/escalated 滚动溯源与升级) |
|
||||
| `tr_courses` / `tr_course_sessions` / `tr_enrollments` | 课程资产 / 场次执行实例 / 名单与完成状态 |
|
||||
| `tr_sign_codes` / `tr_sign_records` / `tr_session_evidence` | 签到码 / 签到流水(异常 flags)/ 培训佐证 |
|
||||
| `tr_templates` | 租户自定义导入模板(demand_collection / question_bank 两键) |
|
||||
| `tr_month_plans` | 月度排期(审批载体与滚动载体;draft/submitted/approved/rejected;annual_plan_id 关联年度计划;roll_from_id 溯源未完成场次/roll_times/escalated 滚动升级;reject_reason/approver_id/approved_at) |
|
||||
| `tr_courses` / `tr_course_sessions` / `tr_enrollments` | 课程资产(含内外培训/厂区/地点/培训次数/外部讲师/计划培训时间/标签等需求同步字段)/ 场次执行实例(month_plan_id 关联排期、notify_mode 通知方式)/ 名单与完成状态(reason/confirmed_by) |
|
||||
| `tr_course_change_logs` | 课程信息修改版本记录(字段级变更明细) |
|
||||
| `tr_sign_codes` / `tr_sign_records` / `tr_session_evidence` | 签到码(token/有效期/围栏)/ 签到流水(abnormal_flags 异常叠加、channel、距离)/ 培训佐证(sign_photo/training_video) |
|
||||
| `tr_question_banks` / `tr_questions` / `tr_papers` / `tr_exam_records` / `tr_wrong_books` | 题库 / 题目 / 试卷(A/B 卷与自学卷)/ 考试记录 / 错题本 |
|
||||
| `tr_learning_tasks` / `tr_learning_progress` / `tr_point_records` / `tr_course_feedbacks` / `tr_lecturer_scores` / `tr_course_time_logs` | 学习任务 / 学习进度 / 积分流水 / 课程答疑 / 讲师月度综合分 / 学习时长 |
|
||||
| `tr_templates` | 租户自定义导入模板(`demand_collection` / `question_bank` 两键) |
|
||||
| `tr_rule_configs` | 业务规则配置(sign_policy/pass_line/roll_policy/point_rules/remind_policy/learning_policy/lecturer_score_weight/role_dict/notify_* 等键) |
|
||||
| `tr_notifications` | 站内通知流水 + 企微推送 outbox(scene/ref 幂等去重,push_status 推送状态机) |
|
||||
|
||||
## 附录 B:主要接口(`/api/v1/training`)
|
||||
## 附录 B:主要接口(`/api/v1/training`,Viewer 门槛 + Contributor 管理动作 + 职称角色细控)
|
||||
|
||||
| 域 | 接口 |
|
||||
| --- | --- |
|
||||
| 计划域 | `GET/POST /demands`、`POST /demands/import`、`POST /demands/:id/confirm`、`DELETE /demands/:id`、`GET/POST /annual-plans(/generate,/progress)`、`GET/POST /month-plans`、`POST /month-plans/:id/approve`、`POST /month-plans/roll` |
|
||||
| 执行域 | `GET/POST /courses`、`POST /courses/:id/publish`、`GET/POST /sessions`、`GET/PUT /sessions/:id/enrollments`、`POST /sessions/:id/sign-code`、`POST /sign-records/checkin`、`POST /sign-records/:id/review`、`GET /sessions/:id/sign-summary`、`POST /evidence/export` |
|
||||
| 查询域 | `GET /dashboards/hr|department|exec`、`GET /courses`(聚合应到/实到与学习/考试状态)、`GET /learning-tasks`、`GET /profile/me` |
|
||||
| 模板域 | `GET /templates`、`GET /templates/:key/file`(下载注入组织下拉)、`POST /templates/:key/upload`、`DELETE /templates/:key`(恢复默认) |
|
||||
| 计划域 | `GET/POST /demands`、`POST /demands/import`(hr/课长)、`POST /demands/:id/confirm`(hr)、`DELETE /demands/:id`(本人或 hr/课长)、`GET /lecturers`、`GET /posts`、`GET /annual-plans`、`POST /annual-plans/generate`(hr)、`GET /annual-plans/progress`、`GET/POST /month-plans`(hr/课长)、`POST /month-plans/:id/approve`(经理/hr)、`POST /month-plans/roll`(hr) |
|
||||
| 课程域 | `GET/POST /courses`、`GET /courses/:id`、`GET /courses/:id/change-logs`、`POST /courses/:id/publish`、`DELETE /courses/:id`、`GET /sessions`、`POST /sessions`、`GET/PUT /sessions/:id/enrollments`、`POST /enrollments/:id/result`、`POST /sessions/:id/notify`(立即推送学员)、`POST /materials`、`POST /materials/upload`、`GET /materials`、`GET /materials/:id/file`、`GET /knowledge-bases` |
|
||||
| 签到域 | `POST /sessions/:id/sign-code`、`GET /sessions/:id/sign-code`、`POST /sign-records/checkin`(member_id 代签)、`GET /sessions/:id/sign-records`、`POST /sign-records/:id/review`、`GET /sessions/:id/sign-summary`、`POST /evidence/export`、`POST/GET /sessions/:id/evidence`、`GET /session-evidences/:id/file`、`DELETE /session-evidences/:id` |
|
||||
| 考试域 | `GET /question-banks`、`POST /question-banks/import`、`POST /question-banks/import-from-kb`、`POST /question-banks/import-generated`、`GET /question-banks/:id/questions`、`POST /papers/generate`、`GET /papers`、`GET /papers/:id/questions`、`POST /papers/:id/answer`、`GET /papers/:id/records`、`POST /exam-records/submit`、`POST /exam-records/submit-for`、`GET /exam-records`、`GET /exam-records/my`、`GET /exam-records/my-list`、`POST /courses/:id/exam-paper`、`GET /courses/:id/papers`、`GET /exams/:session_id/analysis`、`GET /wrong-book`、`POST /courses/:id/generate-questions` |
|
||||
| 学习/画像 | `POST/GET /learning-progress`、`GET /learning-tasks`、`GET /learning-tasks/all`、`POST /course-feedbacks`、`POST /course-feedbacks/:id/reply`、`GET /course-feedbacks/pending`、`GET /profile/me`、`GET /ai-analysis`、`POST /lecturer-scores/settle` |
|
||||
| 查询域 | `GET /dashboards/hr|department|exec`、`GET /courses`(聚合应到/实到与学习/考试状态)、`GET /members/me` |
|
||||
| 组织与成员 | `GET /depts`、`POST /depts`、`DELETE /depts/:id`、`GET /members`、`GET /platform-users`、`POST /members/import`、`PUT /members/:id/roles`、`PUT /members/:id/wecom-userid`、`POST /members/wecom-userid-sync/preview|apply` |
|
||||
| 模板与配置 | `GET /templates`、`GET /templates/:key/file`(下载注入组织下拉)、`POST /templates/:key/upload`、`DELETE /templates/:key`(恢复默认)、`GET /rule-configs`、`POST /rule-configs/seed`、`PUT /rule-configs/:key` |
|
||||
| 通知推送 | `GET /notifications`、`POST /notifications/read`、`POST /notifications/broadcast`、`POST /notifications/push-test`、`POST /notifications/run-weekly`(周一讲师汇总手动触发)、`GET /notifications/push-logs`(推送逐人明细) |
|
||||
|
||||
## 附录 C:月度模板导入(本期新增)改动点摘要
|
||||
## 附录 C:v1.1 版本校准说明(与 v1.0 差异)
|
||||
|
||||
1. 模板资产:新增内置「月度培训排期模板.xlsx」(`internal/assets/trainingtemplates` 增键 `month_schedule`),配置中心可租户自定义替换;
|
||||
2. 解析入库:复用前端 XLSX 解析模式(表头定位 → 行映射 → 部门/讲师名册匹配),新增 `POST /month-plans/import`,逐行生成 `draft` 月度排期;
|
||||
3. 前端入口:计划排期页「批量导入」弹窗增加月度模板下载与上传入口;
|
||||
4. 兼容性:不改动既有月度排期手工排课与审批链路,导入仅是排期的批量建档方式。
|
||||
1. **月度排期模板批量导入未实现**:v1.0 规划的「月度培训排期模板」(内置键 `month_schedule`、接口 `POST /month-plans/import`、计划页导入入口)在当前代码中均不存在(内置模板仅 `demand_collection` / `question_bank` 两键),本版将其移至「规划中」;月度排期后端能力(列表/审批/滚动/场次联动)保留,前端管理入口暂未开放。
|
||||
2. **角色体系校准**:角色为 `hr 人事 / supervisor 课长 / exec 经理 / lecturer 讲师 / trainee 学员`,**文员(clerk)角色已移除**(存量按课长别名对待);`exec` 为「经理」(继承课长权限组)而非 v1.0 表述的「高管」;支持配置中心角色字典与自定义角色权限组继承。
|
||||
3. **年度模板换版**:内置默认模板自 2026-11 起为公司标准「教育训练需求表模板.xlsx」(列:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓/计划培训时间/讲师/备注),非 v1.0 所述「厂区/主办单位/…/培训时间/月份」布局;下拉注入列位为部门 B / 参加人员 D / 讲师 I,且为非阻断式(可自由填写)。
|
||||
4. **导入匹配规则校准**:讲师按**全员名册**匹配(不限讲师名册),命中自动带出部门,未命中落外部讲师(v1.0 的「讲师待分配」备注方案未采用);时间解析基于「计划培训时间」列(含纯月份归一);校验仅针对**部门**(人数/课时不再采集);粘贴导入格式为 `课程名称[,计划培训时间]`。
|
||||
5. **确认链路补全**:确认(仅 hr)除生成年度排期与草稿课程外,还会**生成默认场次并写入参加人员名单、自动授权讲师角色**(v1.0 未描述)。
|
||||
6. **权限校准**:需求导入=hr/课长;确认/滚动/汇总生成排期=hr;月度排期审批=**经理+人事**(非课长);需求收集推送默认勾选人事+课长(非「主管+文员」);纯课长数据范围收窄为本部门。
|
||||
7. **执行域细节校准**:签到代签(member_id)限讲师/课长/人事;佐证照片走平台默认上限(非 50MB)、视频 ≤200MB;及格线配置种子 75(未配置回退 60);佐证包 8 列列名以代码为准。
|
||||
8. **通知体系补全**:站内 + 企微双通道推送(调度器 outbox,T-3/T-1 场次提醒、T-7 讲师维护提醒、周一讲师汇总、立即推送学员、推送记录),v1.0 未覆盖。
|
||||
9. **计划培训月份口径(2026-11 二次调整)**:模板「计划培训时间」列改「**计划培训月份**」(下拉 1~12,非阻断式);标题年份下载时动态置为**下一年度**(2026 年下载即「2027 年度教育训练需求表」);导入/粘贴按月份解析(兼容旧日期格式取月份),年份取收集年度,入库 `planned_time=YYYY-M` 并回填 `expect_month`;在线提报表单改月份下拉(只需选到月份);列表列同步改名「计划培训月份」,确认同步课程时归一 `YYYY-MM`。
|
||||
10. **核验状态口径(2026-11 二次调整)**:填报/导入**统一默认「待核验」**(不再因部门齐全自动置「校验通过」);核验确认权限收紧为**仅经理**(本部门口径),其他角色调用统一提示「暂无权限核验」;已确认行列表文字保持正常色(仅禁止勾选)。
|
||||
11. **数据范围校准(2026-11 二次调整)**:人事/空间管理员查看全部;**经理与课长一致收窄本部门**(原经理为全局视角),覆盖需求/年度排期/月度排期/收集进度列表。
|
||||
12. **模板下拉调整(2026-11 二次调整)**:「课程名称」列下拉取**课程管理**课程名称(隐藏辅助列 CB);「参加人员」列**去掉下拉**(自由填写多人),并清除历史版本注入的 D 列验证。
|
||||
|
||||
## 附录 D:v1.2 调整说明(2026-11 三次调整:唯一编号 / 确认转月度 / 课件试题入课程管理 / 月度计划表单精简)
|
||||
|
||||
### D.1 唯一编号体系
|
||||
|
||||
四类核心实体新增租户内唯一编号(前缀+年月+流水,`tr_code_counters` 计数器 UPSERT 原子递增,migration 000153 含存量回填与计数器播种):
|
||||
|
||||
| 实体 | 编号格式 | 生成时机 |
|
||||
| --- | --- | --- |
|
||||
| 年度需求(年培训计划列表行) | `AP-<year>-####`(按年分段) | 提报/批量导入创建时由服务端生成 |
|
||||
| 月度培训计划(`tr_courses` 承载) | `MP-<YYYYMM>-####`(按授课月份分段,teach_time 缺失取创建月) | 创建计划时生成,不可修改 |
|
||||
| 课程管理条目 | `CRS-####`(租户内流水) | 新增/批量导入时生成;导出 Excel 首列带编号 |
|
||||
| 试题库 | `QB-####`(租户内流水) | Excel 导入/知识库导入/AI 生成建库时统一生成 |
|
||||
|
||||
编号在年培训计划列表与编辑弹窗、月度计划列表与计划详情弹窗(「计划编号」只读展示)、课程管理列表/编辑弹窗(「课程编号」只读)、试题管理抽屉(「题库编号」)同步展示。
|
||||
|
||||
### D.2 经理确认自动转月度培训计划
|
||||
|
||||
沿用年培训计划页签「经理核验」动作(本部门口径校验不变):核验通过后,在原有「生成年度排期行 + 草稿课程」基础上,进一步:
|
||||
|
||||
1. 草稿课程回填 `source_demand_id`(溯源到需求)与 `plan_code` 月度计划编号——即完成「年度计划 → 月度计划」的自动流转;
|
||||
2. 课程管理存在同名课程时自动关联 `library_course_id`(计划侧直接带出并锁定课程信息);无同名课程时由课长在月度计划编辑弹窗手动选择课程管理课程;
|
||||
3. 课长后续在「月培训计划」维护授课安排(见 D.4)。
|
||||
|
||||
### D.3 课件、试题迁入课程管理
|
||||
|
||||
「课程管理」成为课件与试题的统一维护入口(课程信息的一部分):
|
||||
|
||||
- **课件**:课程表单「课件」字段支持名称登记 + 原始文件上传;文档类自动同步知识库「企业培训(课件)」(`tr_course_library.knowledge_id`),支持 AI 对话问答;下载优先走知识库取回,视频仍走原始文件。
|
||||
- **试题**:课程列表新增「试题」入口打开试题管理抽屉,支持题库级与单题级维护:
|
||||
- 题库级:上传试题 Excel(同名重导入整体替换,原件同步知识库「企业培训(题库)」)、从知识库选择导入、AI 课件生成试题(读取课程课件的知识库分块出题,预览编辑后建库)、删除题库(连带题目与缓存试卷);
|
||||
- 单题级:题库内题目列表、单题新增/编辑/删除(题型/题干/选项/答案/分值/难度/知识点/解析),题库冗余题数同步刷新;
|
||||
- 题库经 `tr_question_banks.library_course_id` 挂课程管理条目;月度计划选课后,考试链路按「课程直连题库 → 课程管理条目题库」顺序回退取卷。
|
||||
- 月培训计划的创建/详情弹窗不再提供课件与试题维护入口(原有「关联课件/关联题库(试题)」区块移除);新建计划选择课程时,服务端自动把课程管理课件挂接为计划课件记录(学员学习页与线上发布校验沿用既有链路)。
|
||||
|
||||
### D.4 月度计划表单精简
|
||||
|
||||
- **新增/编辑弹窗**:「计划名称」改「**课程名称**」,从课程管理下拉选择;选择后带出类型/形式/讲师/所属部门/说明并**锁定不可修改**(服务端二次校验覆盖);新增「计划编号」展示(新增时提示保存后自动生成)。
|
||||
- **仅维护六项**:授课时间、授课地点、学员通知、参加人员、学时、学分(线上计划为学习期限替代线下时间地点);「适用部门」随课程管理「所属部门」带出不再手选。
|
||||
- **计划详情弹窗**:头部展示「计划编号」;未关联课程管理的存量计划可在详情中选定课程(选定后锁定);保存仍走全量列更新透传(tags/material_ids/需求同步字段防零值覆盖)。
|
||||
|
||||
### D.5 新增/调整接口
|
||||
|
||||
| 域 | 接口 |
|
||||
| --- | --- |
|
||||
| 课程管理 · 试题 | `GET /course-library/:id/question-banks`(题库列表)、`POST /course-library/:id/question-banks/import`(Excel 导入挂课程)、`POST /course-library/:id/generate-questions`(AI 出题)、`DELETE /question-banks/:id`(删除题库)、`POST /question-banks/:id/questions`(单题新增/编辑)、`DELETE /question-banks/:id/questions/:qid`(删除单题) |
|
||||
| 题库导入扩展 | `POST /question-banks/import`、`/import-from-kb`、`/import-generated` 增加 `library_course_id` 参数(同名替换继承课程/课程管理关联) |
|
||||
| 模型扩展 | `tr_demands.code`、`tr_courses.plan_code/source_demand_id`、`tr_course_library.code/knowledge_id`、`tr_question_banks.code/library_course_id`;计数器表 `tr_code_counters(tenant_id, code_key)`(migration 000153,含唯一部分索引与存量回填) |
|
||||
@@ -13,7 +13,8 @@
|
||||
"test": "tsx --test",
|
||||
"check-i18n": "tsx --test src/i18n/localeKeyAudit.test.ts",
|
||||
"scan-i18n-gaps": "tsx src/i18n/localeGapScan.ts",
|
||||
"regenerate-i18n-locales": "tsx src/i18n/regeneratePrunedLocales.ts"
|
||||
"regenerate-i18n-locales": "tsx src/i18n/regeneratePrunedLocales.ts",
|
||||
"dev:training": "vite --config vite.training-preview.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@microsoft/fetch-event-source": "^2.0.1",
|
||||
|
||||
@@ -157,6 +157,8 @@ export const getMyProfile = () =>
|
||||
export interface TrainingDemand {
|
||||
id: string
|
||||
year: number
|
||||
/** 年计划编号(AP-<year>-####,创建时由服务端生成,列表/详情展示) */
|
||||
code?: string
|
||||
dept_id: string
|
||||
submitter_id: string
|
||||
course_name: string
|
||||
@@ -227,11 +229,15 @@ export interface DeptProgress {
|
||||
export const listDemands = (query?: ListQuery) =>
|
||||
get<{ success: boolean; data: PagedData<TrainingDemand> }>(`${base}/demands`, { params: query })
|
||||
|
||||
/** 需求库实际年份去重列表(降序;年度需求收集页年份下拉数据源,默认选中最新一年)。 */
|
||||
export const listDemandYears = () =>
|
||||
get<{ success: boolean; data: number[] }>(`${base}/demands/years`)
|
||||
|
||||
export const saveDemand = (payload: Partial<TrainingDemand>) =>
|
||||
post<{ success: boolean; data: TrainingDemand }>(`${base}/demands`, payload)
|
||||
|
||||
export const importDemands = (demands: Partial<TrainingDemand>[]) =>
|
||||
post<{ success: boolean; data: { imported: number } }>(`${base}/demands/import`, { demands })
|
||||
post<{ success: boolean; data: { imported: number; notified?: number } }>(`${base}/demands/import`, { demands })
|
||||
|
||||
export const confirmDemand = (id: string) =>
|
||||
post<{ success: boolean; data: TrainingDemand }>(`${base}/demands/${enc(id)}/confirm`, {})
|
||||
@@ -314,6 +320,12 @@ export interface TrainingCourse {
|
||||
lecturer_external?: string
|
||||
/** 备注(需求确认同步) */
|
||||
remark?: string
|
||||
/** 课程管理条目 id(月培训计划「计划名称」从课程管理选择后关联;可空) */
|
||||
library_course_id?: string
|
||||
/** 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成) */
|
||||
plan_code?: string
|
||||
/** 来源需求 id(经理确认自动转月度计划时回填,溯源用) */
|
||||
source_demand_id?: string
|
||||
/** 讲师姓名(联查 users;覆盖不在讲师名册的需求同步讲师) */
|
||||
lecturer_name?: string
|
||||
/** 应到人数(各场次名单去重成员数,列表接口计算) */
|
||||
@@ -406,6 +418,96 @@ export const publishCourse = (id: string) =>
|
||||
export const deleteCourse = (id: string) =>
|
||||
del<{ success: boolean }>(`${base}/courses/${enc(id)}`)
|
||||
|
||||
// ---- 课程管理(课程资产主数据;月培训计划「计划名称」数据源) ----
|
||||
|
||||
/** TrainingLibraryCourse 课程管理条目(000151 tr_course_library)。 */
|
||||
export interface TrainingLibraryCourse {
|
||||
id: string
|
||||
/** 课程编号(CRS-####,创建/导入时由服务端生成,列表/详情展示) */
|
||||
code?: string
|
||||
/** 课程名称(必填) */
|
||||
name: string
|
||||
/** 所属部门(org_depts id;对应需求表「主办单位」,弹窗下拉选择/导入按部门名匹配) */
|
||||
owner_dept_id?: string
|
||||
/** 所属部门名(联查 org_depts 只读) */
|
||||
owner_dept_name?: string
|
||||
/** 说明 */
|
||||
description: string
|
||||
/** 适合人员(对应需求表「参加人员」,自由文本,如:财会人员) */
|
||||
suitable_members?: string
|
||||
/** 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存) */
|
||||
category: string
|
||||
/** 类型:required 必修课 / elective 选修课 */
|
||||
type: 'required' | 'elective'
|
||||
/** 形式:offline 线下 / online 线上 */
|
||||
mode: 'offline' | 'online'
|
||||
/** 讲师(员工 user id;外部讲师落 lecturer_external) */
|
||||
lecturer_id: string
|
||||
/** 外部讲师姓名(导入未匹配到员工名册时) */
|
||||
lecturer_external?: string
|
||||
/** 时长(学时) */
|
||||
hours: number
|
||||
/** 课件名称登记(多个用、分隔;对应需求表「课件收集」) */
|
||||
material_name?: string
|
||||
/** 课件文件(可上传,经专端点下载) */
|
||||
file_name?: string
|
||||
file_size?: number
|
||||
/** 课件同步知识库「企业培训(课件)」后的文档 id(AI 出题依赖) */
|
||||
knowledge_id?: string
|
||||
/** 发布状态(000154):draft 草稿/published 已发布/offline 已下线 */
|
||||
publish_status?: string
|
||||
/** 移除课件文件标记(保存时置 true 强制清空文件) */
|
||||
clear_file?: boolean
|
||||
/** 讲师姓名(联查 users 只读) */
|
||||
lecturer_name?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export const listCourseLibrary = (query?: ListQuery) =>
|
||||
get<{ success: boolean; data: PagedData<TrainingLibraryCourse> }>(`${base}/course-library`, { params: query })
|
||||
|
||||
export const saveCourseLibraryItem = (payload: Partial<TrainingLibraryCourse>) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library`, payload)
|
||||
|
||||
export const deleteCourseLibraryItem = (id: string) =>
|
||||
del<{ success: boolean }>(`${base}/course-library/${enc(id)}`)
|
||||
|
||||
/** 课程条目发布(000154):发布后进入培训中心「和信课程」目录。 */
|
||||
export const publishCourseLibraryItem = (id: string) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library/${enc(id)}/publish`)
|
||||
|
||||
/** 课程条目下线(000154):从培训中心「和信课程」目录撤回。 */
|
||||
export const offlineCourseLibraryItem = (id: string) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library/${enc(id)}/offline`)
|
||||
|
||||
/** 批量导入(前端解析 Excel 后逐行提交,与需求导入同口径;返回导入条数)。 */
|
||||
export const importCourseLibrary = (items: Partial<TrainingLibraryCourse>[]) =>
|
||||
post<{ success: boolean; data: { imported: number } }>(`${base}/course-library/import`, { items })
|
||||
|
||||
/** 导出 Excel(ids 空 = 全量;当前筛选由调用方传当前列表 id)。Blob 交给调用方触发保存。 */
|
||||
export const exportCourseLibrary = (ids: string[]) =>
|
||||
post(`${base}/course-library/export`, { ids }, { responseType: 'blob' })
|
||||
|
||||
/** 上传课件原始文件(multipart;名称登记为空时后端以文件名兜底;文档类同步知识库)。 */
|
||||
export const uploadCourseLibraryMaterial = (id: string, formData: FormData) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(
|
||||
`${base}/course-library/${enc(id)}/material`,
|
||||
formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
)
|
||||
|
||||
/** 从知识库「企业培训(课件)」选择已有文档作为课件(与上传同步同口径)。 */
|
||||
export const attachCourseLibraryMaterialFromKb = (id: string, payload: { knowledge_id: string }) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(
|
||||
`${base}/course-library/${enc(id)}/material/from-kb`,
|
||||
payload,
|
||||
)
|
||||
|
||||
/** 课件原始文件下载(在线预览/保存)。 */
|
||||
export const downloadCourseLibraryMaterial = (id: string) =>
|
||||
getDown(`${base}/course-library/${enc(id)}/material/file`)
|
||||
|
||||
export const listSessions = (query?: ListQuery) =>
|
||||
get<{ success: boolean; data: TrainingCourseSession[] }>(`${base}/sessions`, { params: query })
|
||||
|
||||
@@ -579,9 +681,13 @@ export const deleteSessionEvidence = (evidenceId: string) =>
|
||||
|
||||
export interface TrainingQuestionBank {
|
||||
id: string
|
||||
/** 试题库编号(QB-####,导入/生成时由服务端生成) */
|
||||
code?: string
|
||||
name: string
|
||||
dept_id: string
|
||||
course_id: string
|
||||
/** 课程管理条目 id(试题随课程管理维护,可与 course_id 并存) */
|
||||
library_course_id?: string
|
||||
/** 非空表示该题库 Excel 已同步进「企业培训(题库)」知识库 */
|
||||
knowledge_id: string
|
||||
question_count: number
|
||||
@@ -639,11 +745,12 @@ export const importQuestionBankExcel = (formData: FormData) =>
|
||||
})
|
||||
|
||||
// ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档解析建题库
|
||||
// (未传 course_id 时继承同名旧题库的课程关联)。
|
||||
// (未传 course_id/library_course_id 时继承同名旧题库的关联)。
|
||||
export const importQuestionBankFromKnowledge = (payload: {
|
||||
knowledge_id: string
|
||||
name?: string
|
||||
course_id?: string
|
||||
library_course_id?: string
|
||||
}) =>
|
||||
post<{ success: boolean; data: TrainingQuestionBank }>(`${base}/question-banks/import-from-kb`, payload)
|
||||
|
||||
@@ -651,9 +758,17 @@ export const importQuestionBankFromKnowledge = (payload: {
|
||||
export const generateCourseQuestions = (courseId: string, payload: { material_id: string; count?: number }) =>
|
||||
post<{ success: boolean; data: TrainingQuestion[] }>(`${base}/courses/${enc(courseId)}/generate-questions`, payload)
|
||||
|
||||
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(课件需已同步知识库,000153)。
|
||||
export const generateLibraryCourseQuestions = (libraryCourseId: string, payload?: { count?: number }) =>
|
||||
post<{ success: boolean; data: TrainingQuestion[] }>(
|
||||
`${base}/course-library/${enc(libraryCourseId)}/generate-questions`,
|
||||
payload ?? {},
|
||||
)
|
||||
|
||||
// ImportGeneratedQuestionBank 使用生成/编辑后的题目建题库(关联课程,文本同步知识库)。
|
||||
export const importGeneratedQuestionBank = (payload: {
|
||||
course_id?: string
|
||||
library_course_id?: string
|
||||
name?: string
|
||||
questions: TrainingQuestion[]
|
||||
}) =>
|
||||
@@ -662,6 +777,47 @@ export const importGeneratedQuestionBank = (payload: {
|
||||
export const listQuestions = (bankId: string) =>
|
||||
get<{ success: boolean; data: TrainingQuestion[] }>(`${base}/question-banks/${enc(bankId)}/questions`)
|
||||
|
||||
// ---- 课程管理 · 试题维护(000153) ----
|
||||
|
||||
/** 课程条目下的题库列表(试题维护抽屉)。 */
|
||||
export const listLibraryCourseQuestionBanks = (libraryCourseId: string) =>
|
||||
get<{ success: boolean; data: TrainingQuestionBank[] }>(
|
||||
`${base}/course-library/${enc(libraryCourseId)}/question-banks`,
|
||||
)
|
||||
|
||||
/** 更换课程条目的试题(所选题库整体替换,000156;月计划详情「试题·更换」入口)。 */
|
||||
export const linkLibraryCourseQuestionBank = (libraryCourseId: string, bankId: string) =>
|
||||
put<{ success: boolean; data: TrainingQuestionBank[] }>(
|
||||
`${base}/course-library/${enc(libraryCourseId)}/question-banks/link`,
|
||||
{ bank_id: bankId },
|
||||
)
|
||||
|
||||
/** Excel 导入题库并挂课程管理条目(同名重导入即替换)。 */
|
||||
export const importLibraryCourseQuestionBank = (libraryCourseId: string, formData: FormData) =>
|
||||
post<{ success: boolean; data: TrainingQuestionBank }>(
|
||||
`${base}/course-library/${enc(libraryCourseId)}/question-banks/import`,
|
||||
formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
)
|
||||
|
||||
/** 删除题库(连带题目与缓存试卷)。 */
|
||||
export const deleteQuestionBank = (bankId: string) =>
|
||||
del<{ success: boolean }>(`${base}/question-banks/${enc(bankId)}`)
|
||||
|
||||
/** 单题新增/编辑(id 空 = 新增;题库 question_count 同步刷新)。 */
|
||||
export const saveQuestion = (
|
||||
bankId: string,
|
||||
payload: Partial<TrainingQuestion> & { id?: string },
|
||||
) =>
|
||||
post<{ success: boolean; data: TrainingQuestion }>(
|
||||
`${base}/question-banks/${enc(bankId)}/questions`,
|
||||
payload,
|
||||
)
|
||||
|
||||
/** 删除单题。 */
|
||||
export const deleteQuestion = (bankId: string, questionId: string) =>
|
||||
del<{ success: boolean }>(`${base}/question-banks/${enc(bankId)}/questions/${enc(questionId)}`)
|
||||
|
||||
export const generatePaper = (bankId: string, sessionId: string, count: number, version: string) =>
|
||||
post<{ success: boolean; data: TrainingPaper }>(`${base}/papers/generate`, {
|
||||
bank_id: bankId,
|
||||
@@ -1009,6 +1165,36 @@ export async function fetchRoleDict(): Promise<TrainingRoleDef[]> {
|
||||
return DEFAULT_ROLE_DICT
|
||||
}
|
||||
|
||||
/** 课程分类字典 rule-configs 键(与后端 RuleKeyCourseCategoryDict 一致)。 */
|
||||
export const COURSE_CATEGORY_DICT_RULE_KEY = 'course_category_dict'
|
||||
|
||||
/** 课程分类默认字典(与后端 DefaultCourseCategories 一致;配置缺失/损坏时兜底)。 */
|
||||
export const DEFAULT_COURSE_CATEGORIES: string[] = [
|
||||
'专业技能类',
|
||||
'企业文化与制度类',
|
||||
'通用技能类',
|
||||
'安全与健康类',
|
||||
'管理领导类',
|
||||
'行业与产品知识类',
|
||||
]
|
||||
|
||||
/** 读取课程分类字典(rule-configs 中的 course_category_dict;缺失/损坏回退默认分类,
|
||||
* 配置中心「课程分类」卡保存后自然生效) */
|
||||
export async function fetchCourseCategories(): Promise<string[]> {
|
||||
try {
|
||||
const res = await listRuleConfigs()
|
||||
const configs = unwrap<TrainingRuleConfig[]>(res) || []
|
||||
const categories = configs.find((c) => c.rule_key === COURSE_CATEGORY_DICT_RULE_KEY)?.rule_value?.categories
|
||||
if (Array.isArray(categories)) {
|
||||
const list = categories.filter((c): c is string => typeof c === 'string' && !!c.trim())
|
||||
if (list.length > 0) return list
|
||||
}
|
||||
} catch {
|
||||
// 拉取失败回退默认分类,课程筛选与表单下拉不受影响
|
||||
}
|
||||
return DEFAULT_COURSE_CATEGORIES
|
||||
}
|
||||
|
||||
/** 沿权限分配(inherits)传递展开角色 → 权限并集(与后端 ExpandRoles 同构,环安全);
|
||||
* 存量 clerk 角色按别名映射为课长 */
|
||||
export function expandRoles(roles: string[], dict: TrainingRoleDef[]): string[] {
|
||||
@@ -1035,7 +1221,7 @@ export function roleLabelOf(key: string, dict: TrainingRoleDef[], narrow = false
|
||||
|
||||
// ---- 配置中心 · 导入模板管理 ----
|
||||
|
||||
export type TrainingTemplateKey = 'demand_collection' | 'question_bank'
|
||||
export type TrainingTemplateKey = 'demand_collection' | 'question_bank' | 'course_library'
|
||||
|
||||
export interface TrainingTemplateMeta {
|
||||
template_key: TrainingTemplateKey
|
||||
|
||||
@@ -605,10 +605,12 @@ const moreToolItems = computed<MenuItem[]>(() => {
|
||||
const items = MORE_TOOLS_ORDER
|
||||
.map(path => all.find((item: MenuItem) => item.path === path))
|
||||
.filter((item): item is MenuItem => !!item);
|
||||
// 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底
|
||||
// 末位固定追加「配置中心」「职称角色」「组织架构」;「共享空间」还原至最底
|
||||
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
|
||||
// 职称角色(000159):自「企业培训」分组迁入,置于配置中心之后
|
||||
const MEMBERS_TOOL_ITEM: MenuItem = { title: '职称角色', icon: 'training', path: 'training/members' };
|
||||
const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations');
|
||||
return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
||||
return [...items, RULES_TOOL_ITEM, MEMBERS_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
||||
});
|
||||
|
||||
// 菜单图标统一映射:顶层项与「更多工具」子项共用
|
||||
@@ -632,12 +634,14 @@ const iconSrcFor = (icon: string): string => {
|
||||
// 文案与培训页内 tab 保持一致;组织成员由 Training 页内按角色控制内容。
|
||||
// 「配置中心」已移入「更多工具」末位(RULES_TOOL_ITEM),不再出现在本分组。
|
||||
const TRAINING_TABS: { key: string; title: string }[] = [
|
||||
{ key: 'dashboard', title: '工作台' },
|
||||
{ key: 'plan', title: '培训计划' },
|
||||
{ key: 'course', title: '培训课程' },
|
||||
{ key: 'dashboard', title: '培训中心' },
|
||||
{ key: 'plan', title: '年培训计划' },
|
||||
{ key: 'course', title: '月培训计划' },
|
||||
{ key: 'library', title: '课程管理' },
|
||||
{ key: 'sign', title: '培训签到' },
|
||||
{ key: 'study', title: '学习考试' },
|
||||
{ key: 'members', title: '职称角色' },
|
||||
// 数据驾驶舱(000158):自培训中心页头切换迁入侧栏
|
||||
{ key: 'data-dashboard', title: '数据驾驶舱' },
|
||||
// 职称角色(000159):迁至「更多工具」分组、配置中心之后(角色权限口径)
|
||||
];
|
||||
const TRAINING_GROUP_TITLE = '企业培训';
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useAuthStore } from '@/stores/auth'
|
||||
import WorkbenchPanel from '@/views/training/components/WorkbenchPanel.vue'
|
||||
import PlanPanel from '@/views/training/components/PlanPanel.vue'
|
||||
import CoursePanel from '@/views/training/components/CoursePanel.vue'
|
||||
import LibraryPanel from '@/views/training/components/LibraryPanel.vue'
|
||||
import StudyPanel from '@/views/training/components/StudyPanel.vue'
|
||||
import RulePanel from '@/views/training/components/RulePanel.vue'
|
||||
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||
@@ -35,13 +36,14 @@ const HARNESS_APP = defineComponent({
|
||||
|
||||
type WorkbenchView = 'course' | 'growth' | 'dashboard'
|
||||
const workbenchTab = ref<WorkbenchView>('course')
|
||||
// 子页:工作台 / 培训计划 / 培训课程 / 学习考试 / 配置中心
|
||||
const page = ref<'workbench' | 'plan' | 'course' | 'study' | 'rules'>('workbench')
|
||||
// 子页:培训中心 / 年培训计划 / 月培训计划 / 课程管理 / 学习考试 / 配置中心
|
||||
const page = ref<'workbench' | 'plan' | 'course' | 'library' | 'study' | 'rules'>('workbench')
|
||||
|
||||
const PAGES = [
|
||||
{ key: 'workbench', title: '工作台' },
|
||||
{ key: 'plan', title: '培训计划' },
|
||||
{ key: 'course', title: '培训课程' },
|
||||
{ key: 'workbench', title: '培训中心' },
|
||||
{ key: 'plan', title: '年培训计划' },
|
||||
{ key: 'course', title: '月培训计划' },
|
||||
{ key: 'library', title: '课程管理' },
|
||||
{ key: 'study', title: '学习考试' },
|
||||
{ key: 'rules', title: '配置中心' },
|
||||
] as const
|
||||
@@ -62,8 +64,8 @@ const HARNESS_APP = defineComponent({
|
||||
const meta = computed(() => {
|
||||
if (isWorkbench.value) {
|
||||
if (workbenchTab.value === 'course') return { title: '培训课程', desc: '课程/课件上传后自动转入课件库并智能归档' }
|
||||
if (workbenchTab.value === 'growth') return { title: '工作台', desc: '个人成长进阶 · 能力模型与成就任务总览' }
|
||||
return { title: '工作台', desc: '培训运营总览、待办与达成率一览' }
|
||||
if (workbenchTab.value === 'growth') return { title: '培训中心', desc: '个人成长进阶 · 能力模型与成就任务总览' }
|
||||
return { title: '培训中心', desc: '培训运营总览、待办与达成率一览' }
|
||||
}
|
||||
const found = PAGES.find((p) => p.key === page.value)
|
||||
return { title: found?.title || '', desc: '' }
|
||||
@@ -74,6 +76,7 @@ const HARNESS_APP = defineComponent({
|
||||
switch (key) {
|
||||
case 'plan': return h(PlanPanel, common)
|
||||
case 'course': return h(CoursePanel, common)
|
||||
case 'library': return h(LibraryPanel, common)
|
||||
case 'study': return h(StudyPanel, common)
|
||||
case 'rules': return h(RulePanel, common)
|
||||
default: return h(WorkbenchPanel, { ...common, tab: workbenchTab.value })
|
||||
|
||||
@@ -15,47 +15,51 @@ export const TRAINING_MOCK = {
|
||||
{ id: 'dept-a', tenant_id: 1, parent_id: '', name: '冲压车间', code: 'CY', sort: 1 },
|
||||
{ id: 'dept-b', tenant_id: 1, parent_id: '', name: '技术部', code: 'JS', sort: 2 },
|
||||
],
|
||||
demands: [
|
||||
{ id: 'd1', code: `AP-${NOW.getFullYear()}-0001`, year: NOW.getFullYear(), dept_id: 'dept-a', dept_name: '冲压车间', submitter_id: 'm1', course_name: '叉车年度复训', post_scope: '叉车操作员', lecturer_name: '', planned_time: `${NOW.getFullYear() + 1}-3`, train_type: '内部', location: '一楼展厅', remark: '', check_status: 'pending', check_msg: '', status: 'submitted' },
|
||||
{ id: 'd2', code: `AP-${NOW.getFullYear()}-0002`, year: NOW.getFullYear(), dept_id: 'dept-b', dept_name: '技术部', submitter_id: 'm3', course_name: '品质工具(APQP)专题', post_scope: '品质岗', lecturer_name: '', planned_time: `${NOW.getFullYear() + 1}-5`, train_type: '外部', location: '技术部实训区', remark: '', check_status: 'passed', check_msg: '', status: 'confirmed' },
|
||||
],
|
||||
courses: [
|
||||
{
|
||||
id: 'c1', code: 'TR-001', name: '冲压B车间安全生产教育培训', mode: 'online', type: 'required',
|
||||
lecturer_id: 'm1', hours: 0.75, credits: 1, exam_enabled: true, dept_ids: ['dept-a'],
|
||||
id: 'c1', code: 'CRS-0001', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0001`, name: '冲压B车间安全生产教育培训', mode: 'online', type: 'required',
|
||||
lecturer_id: 'u-m1', hours: 0.75, credits: 1, exam_enabled: true, dept_ids: ['dept-a'],
|
||||
post_scope: '全员必修', description: '', material_ids: ['mt1'], tags: ['安全'], status: 'published',
|
||||
creator_id: '', created_at: month(0, 2), updated_at: month(0, 2),
|
||||
},
|
||||
{
|
||||
id: 'c2', code: 'TR-002', name: '六轴机械手调试培训', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'm2', hours: 4, credits: 2, exam_enabled: false, dept_ids: ['dept-b'],
|
||||
id: 'c2', code: 'CRS-0002', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0002`, name: '六轴机械手调试培训', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'u-m2', hours: 4, credits: 2, exam_enabled: false, dept_ids: ['dept-b'],
|
||||
post_scope: '技术级以上', description: '', material_ids: [], tags: ['技能'], status: 'published',
|
||||
creator_id: '', created_at: month(-1, 20), updated_at: month(-1, 20),
|
||||
},
|
||||
{
|
||||
id: 'c3', code: 'TR-003', name: 'TOPGP系统培训', mode: 'online', type: 'elective',
|
||||
lecturer_id: 'm1', hours: 0.5, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
id: 'c3', code: 'CRS-0003', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0003`, name: 'TOPGP系统培训', mode: 'online', type: 'elective',
|
||||
lecturer_id: 'u-m1', hours: 0.5, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
post_scope: '', description: '', material_ids: [], tags: ['系统'], status: 'published',
|
||||
creator_id: '', created_at: month(-2, 11), updated_at: month(-2, 11),
|
||||
},
|
||||
{
|
||||
id: 'c4', code: 'TR-004', name: '产品品质培训(冲压)', mode: 'online', type: 'required',
|
||||
lecturer_id: 'm1', hours: 0.67, credits: 1, exam_enabled: true, dept_ids: ['dept-a'],
|
||||
id: 'c4', code: 'CRS-0004', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0004`, name: '产品品质培训(冲压)', mode: 'online', type: 'required',
|
||||
lecturer_id: 'u-m1', hours: 0.67, credits: 1, exam_enabled: true, dept_ids: ['dept-a'],
|
||||
post_scope: '品质岗', description: '', material_ids: ['mt2', 'mt3'], tags: ['品质'], status: 'published',
|
||||
creator_id: '', created_at: month(0, 28), updated_at: month(0, 28),
|
||||
},
|
||||
{
|
||||
id: 'c5', code: 'TR-005', name: '组装安全生产教育训练', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'm3', hours: 2, credits: 1, exam_enabled: false, dept_ids: ['dept-a'],
|
||||
id: 'c5', code: 'CRS-0005', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0005`, name: '组装安全生产教育训练', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'u-m3', hours: 2, credits: 1, exam_enabled: false, dept_ids: ['dept-a'],
|
||||
post_scope: '全员必修', description: '', material_ids: [], tags: ['安全'], status: 'published',
|
||||
creator_id: '', created_at: month(0, 5), updated_at: month(0, 5),
|
||||
},
|
||||
{
|
||||
id: 'c6', code: 'TR-006', name: '新员工入职引导', mode: 'online', type: 'required',
|
||||
lecturer_id: 'm3', hours: 1, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
id: 'c6', code: 'CRS-0006', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0006`, name: '新员工入职引导', mode: 'online', type: 'required',
|
||||
lecturer_id: 'u-m3', hours: 1, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
post_scope: '全员必修', description: '', material_ids: ['mt4'], tags: ['入职'], status: 'published',
|
||||
creator_id: '', created_at: month(0, 30), updated_at: month(0, 30),
|
||||
},
|
||||
// 草稿课程:目录页仅展示已发布课程,此条应被前端过滤
|
||||
{
|
||||
id: 'c7', code: 'TR-007', name: '模具保养必修课(草稿)', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'm2', hours: 2, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
id: 'c7', code: 'CRS-0007', plan_code: `MP-${NOW.getFullYear()}${String(NOW.getMonth() + 1).padStart(2, '0')}-0007`, name: '模具保养必修课(草稿)', mode: 'offline', type: 'required',
|
||||
lecturer_id: 'u-m2', hours: 2, credits: 1, exam_enabled: false, dept_ids: [],
|
||||
post_scope: '', description: '', material_ids: [], tags: [], status: 'draft',
|
||||
creator_id: '', created_at: month(0, 1), updated_at: month(0, 1),
|
||||
},
|
||||
@@ -138,9 +142,9 @@ export const TRAINING_MOCK = {
|
||||
generated_at: '',
|
||||
},
|
||||
sessions: [
|
||||
{ id: 's1', course_id: 'c2', month_plan_id: '', year: NOW.getFullYear(), month: NOW.getMonth() + 1, start_at: month(1, 12), end_at: month(1, 12), location: '3号厂房 · 二楼培训室', online_url: '', capacity: 0, lecturer_id: 'm2', status: 'scheduled' },
|
||||
{ id: 's2', course_id: 'c2', month_plan_id: '', year: NOW.getFullYear() - 1, month: 12, start_at: month(-2, 8), end_at: month(-2, 8), location: '技术部实训区', online_url: '', capacity: 0, lecturer_id: 'm2', status: 'finished' },
|
||||
{ id: 's3', course_id: 'c5', month_plan_id: '', year: NOW.getFullYear() - 1, month: 10, start_at: month(-1, 15), end_at: month(-1, 15), location: '一楼展厅', online_url: '', capacity: 0, lecturer_id: 'm3', status: 'finished' },
|
||||
{ id: 's1', course_id: 'c2', month_plan_id: '', year: NOW.getFullYear(), month: NOW.getMonth() + 1, start_at: month(1, 12), end_at: month(1, 12), location: '3号厂房 · 二楼培训室', online_url: '', capacity: 0, lecturer_id: 'u-m2', status: 'scheduled' },
|
||||
{ id: 's2', course_id: 'c2', month_plan_id: '', year: NOW.getFullYear() - 1, month: 12, start_at: month(-2, 8), end_at: month(-2, 8), location: '技术部实训区', online_url: '', capacity: 0, lecturer_id: 'u-m2', status: 'finished' },
|
||||
{ id: 's3', course_id: 'c5', month_plan_id: '', year: NOW.getFullYear() - 1, month: 10, start_at: month(-1, 15), end_at: month(-1, 15), location: '一楼展厅', online_url: '', capacity: 0, lecturer_id: 'u-m3', status: 'finished' },
|
||||
],
|
||||
hrDashboard: {
|
||||
demand_progress: [
|
||||
@@ -159,6 +163,52 @@ export const TRAINING_MOCK = {
|
||||
},
|
||||
}
|
||||
|
||||
// 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致)
|
||||
const COURSE_LIBRARY_MOCK = [
|
||||
{ id: 'lib-1', code: 'CRS-0001', name: '新员工入职通识培训', owner_dept_id: 'dept-b', owner_dept_name: '技术部', description: '公司制度、企业文化与办公系统入门', suitable_members: '新入职员工', category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) },
|
||||
{ id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) },
|
||||
{ id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) },
|
||||
]
|
||||
|
||||
// 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####)
|
||||
const QUESTION_BANKS_MOCK = [
|
||||
{ id: 'b1', code: 'QB-0001', name: '新员工入职通识题库', dept_id: '', course_id: '', library_course_id: 'lib-1', knowledge_id: '', question_count: 2, created_at: month(0, 3), updated_at: month(0, 3) },
|
||||
{ id: 'b2', code: 'QB-0002', name: '冲压安全操作题库', dept_id: '', course_id: '', library_course_id: 'lib-2', knowledge_id: '', question_count: 1, created_at: month(0, 6), updated_at: month(0, 6) },
|
||||
]
|
||||
const QUESTIONS_MOCK: Record<string, unknown[]> = {
|
||||
b1: [
|
||||
{ id: 'q1', bank_id: 'b1', seq_no: 1, type: 'single', stem: '公司带薪年休假的天数由什么确定?', options: ['A. 入职年限', 'B. 累计工作年限', 'C. 岗位等级', 'D. 部门规定'], answer: 'B', score: 5, difficulty: 2, knowledge_point: '考勤休假', analysis: '' },
|
||||
{ id: 'q2', bank_id: 'b1', seq_no: 2, type: 'multiple', stem: '入职引导包含哪些内容?', options: ['A. 企业文化', 'B. 安全规范', 'C. 办公系统', 'D. 薪酬谈判'], answer: 'ABC', score: 5, difficulty: 3, knowledge_point: '入职引导', analysis: '' },
|
||||
],
|
||||
b2: [
|
||||
{ id: 'q3', bank_id: 'b2', seq_no: 1, type: 'judge', stem: '冲压机双手启动按钮可以短接使用。', options: ['A. 对', 'B. 错'], answer: 'B', score: 5, difficulty: 1, knowledge_point: '安全操作规范', analysis: '严禁短接安全装置。' },
|
||||
],
|
||||
}
|
||||
|
||||
// 规则配置(配置中心):预览 harness 回课程分类字典与职称角色字典,
|
||||
// 其余键缺省由前端 DEFAULT_RULE_VALUES 打底
|
||||
const RULE_CONFIGS_MOCK = [
|
||||
{
|
||||
rule_key: 'course_category_dict',
|
||||
rule_value: { categories: ['专业技能类', '企业文化与制度类', '通用技能类', '安全与健康类', '管理领导类', '行业与产品知识类'] },
|
||||
updated_by: '',
|
||||
updated_at: month(0, 1),
|
||||
},
|
||||
{
|
||||
rule_key: 'role_dict',
|
||||
rule_value: {
|
||||
roles: [
|
||||
{ key: 'hr', label: '人事', short: '人事', system: true },
|
||||
{ key: 'supervisor', label: '课长', short: '课长', system: true },
|
||||
{ key: 'lecturer', label: '讲师', short: '讲师', system: true },
|
||||
{ key: 'exec', label: '经理', short: '经理', system: true, inherits: ['supervisor'] },
|
||||
],
|
||||
},
|
||||
updated_by: '',
|
||||
updated_at: month(0, 1),
|
||||
},
|
||||
]
|
||||
|
||||
// 配置中心 · 导入模板元数据(harness 固定展示内置默认;上传/删除不落库,刷新即还原)
|
||||
const TEMPLATE_METAS = [
|
||||
{
|
||||
@@ -177,12 +227,30 @@ const TEMPLATE_METAS = [
|
||||
updated_by: '',
|
||||
source: 'default',
|
||||
},
|
||||
{
|
||||
template_key: 'course_library',
|
||||
file_name: '课程管理导入模板.xlsx',
|
||||
file_size: 16593,
|
||||
updated_at: '',
|
||||
updated_by: '',
|
||||
source: 'default',
|
||||
},
|
||||
]
|
||||
|
||||
// 返回 { matched, body };未匹配返回 null 由 vite 放行
|
||||
export function resolveTrainingMock(method: string, url: string): { status: number; body: unknown } | null {
|
||||
const ok = (data: unknown) => ({ status: 200, body: { success: true, data } })
|
||||
if (!url.startsWith('/api/v1/training/')) return null
|
||||
if (!url.startsWith('/api/v1/training/')) {
|
||||
// 知识库文档列表(课程管理「从知识库选择课件」用,预览演示数据)
|
||||
if (url.startsWith('/api/v1/knowledge-bases/') && url.includes('/knowledge')) {
|
||||
return ok([
|
||||
{ id: 'kbdoc-1', title: '入职通识手册', file_name: '入职通识手册.pptx' },
|
||||
{ id: 'kbdoc-2', title: '安全操作规程', file_name: '安全操作规程.docx' },
|
||||
{ id: 'kbdoc-3', title: 'IATF16949 体系要点', file_name: 'IATF16949体系要点.pdf' },
|
||||
])
|
||||
}
|
||||
return null
|
||||
}
|
||||
// 模板二进制下载由 vite 配置里的中间件直接回文件,不经过本函数
|
||||
if (url === '/api/v1/training/templates' || url.endsWith('/templates')) {
|
||||
if (method === 'GET') return ok(TEMPLATE_METAS)
|
||||
@@ -190,6 +258,27 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
|
||||
}
|
||||
if (method === 'GET') {
|
||||
if (url.includes('/depts')) return ok(TRAINING_MOCK.depts)
|
||||
// 规则配置(配置中心):课程分类字典 + 职称角色字典
|
||||
if (url.includes('/rule-configs')) return ok(RULE_CONFIGS_MOCK)
|
||||
// 系统默认知识库(课件/题库)摘要
|
||||
if (url.includes('/knowledge-bases')) {
|
||||
return ok({
|
||||
courseware: { id: 'kb-courseware', name: '企业培训(课件)', source: 'training_courseware' },
|
||||
question_bank: { id: 'kb-question', name: '企业培训(题库)', source: 'training_question_bank' },
|
||||
})
|
||||
}
|
||||
// 课程管理 · 试题维护(000153):课程条目题库列表 / 题库题目列表,须先于
|
||||
// /course-library、/question-banks 通用匹配
|
||||
if (url.includes('/question-banks/') && url.includes('/questions')) {
|
||||
const bankId = url.split('/question-banks/')[1]?.split('/')[0] || ''
|
||||
return ok(QUESTIONS_MOCK[bankId] || [])
|
||||
}
|
||||
if (url.includes('/course-library/') && url.includes('/question-banks')) {
|
||||
const courseId = url.split('/course-library/')[1]?.split('/')[0] || ''
|
||||
return ok(QUESTION_BANKS_MOCK.filter((b) => !courseId || b.library_course_id === courseId))
|
||||
}
|
||||
// 课程管理列表(月培训计划「课程名称」数据源)
|
||||
if (url.includes('/course-library')) return ok({ items: COURSE_LIBRARY_MOCK, total: COURSE_LIBRARY_MOCK.length })
|
||||
// 学习任务:/learning-tasks/all 为管理端课程学习情况,须先于 /learning-tasks 匹配
|
||||
if (url.includes('/learning-tasks/all')) return ok(TRAINING_MOCK.courseLearning)
|
||||
if (url.includes('/learning-tasks')) return ok(TRAINING_MOCK.myTasks)
|
||||
@@ -215,8 +304,17 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
|
||||
if (url.includes('/dashboards')) return ok({})
|
||||
if (url.includes('/courses')) return ok({ items: TRAINING_MOCK.courses, total: TRAINING_MOCK.courses.length })
|
||||
if (url.includes('/sessions')) return ok(TRAINING_MOCK.sessions)
|
||||
// 年度需求收集:/demands/years 须先于 /demands 匹配(预览无历史数据,年份回当前年)
|
||||
if (url.includes('/demands/years')) return ok([NOW.getFullYear()])
|
||||
if (url.includes('/demands')) return ok({ items: TRAINING_MOCK.demands, total: TRAINING_MOCK.demands.length })
|
||||
return ok(null)
|
||||
}
|
||||
// POST(快速建课/发布/课件登记)统一回成功
|
||||
// POST/DELETE(快速建课/发布/课件登记/试题维护)统一回成功;单题保存回显入参题目
|
||||
if (url.includes('/question-banks/') && url.includes('/questions')) {
|
||||
return ok({ id: `q-new-${Date.now()}`, seq_no: 0 })
|
||||
}
|
||||
if (url.includes('/course-library/') && url.includes('/question-banks/import')) {
|
||||
return ok({ id: `b-new-${Date.now()}`, code: `QB-${String(QUESTION_BANKS_MOCK.length + 1).padStart(4, '0')}`, name: '新导入题库', question_count: 5 })
|
||||
}
|
||||
return ok({ id: `c-new-${Date.now()}` })
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
</h2>
|
||||
<t-tag v-if="myRoleLabel" theme="primary" variant="light">{{ myRoleLabel }}</t-tag>
|
||||
</div>
|
||||
<!-- 工作台视图切换:课程 / 个人成长 / 数据驾驶舱(驾驶舱仅培训管理角色可见) -->
|
||||
<!-- 工作台视图切换:课程 / 个人成长(数据驾驶舱已迁侧栏,000158) -->
|
||||
<nav v-if="isWorkbench" class="workbench-switch" aria-label="工作台视图切换">
|
||||
<button
|
||||
v-for="t in workbenchSwitchTabs"
|
||||
@@ -26,7 +26,7 @@
|
||||
<p class="training-subtitle">{{ activeTabMeta.desc }}</p>
|
||||
</header>
|
||||
|
||||
<!-- 子页(工作台/培训计划/…/配置中心)由侧栏「企业培训」分组导航,此处按路由 tab 参数渲染 -->
|
||||
<!-- 子页(培训中心/年培训计划/…/配置中心)由侧栏「企业培训」分组导航,此处按路由 tab 参数渲染 -->
|
||||
<t-alert
|
||||
v-if="sessionExpired"
|
||||
class="training-session-alert"
|
||||
@@ -35,15 +35,24 @@
|
||||
description="培训数据未丢失。请重新登录后刷新本页即可查看。"
|
||||
/>
|
||||
<div class="training-body">
|
||||
<!-- 工作台:课程(默认)/个人成长/数据驾驶舱 三视图自由切换 -->
|
||||
<!-- 工作台:课程(默认)/个人成长 两视图切换;数据驾驶舱已迁侧栏(000158) -->
|
||||
<WorkbenchPanel v-if="activeTab === 'dashboard'" :roles="myRoles" :admin="isAdmin" :tab="workbenchTab" />
|
||||
<!-- 数据驾驶舱独立子页(000158):与工作台驾驶舱视图同源,非管理角色回落课程目录 -->
|
||||
<template v-else-if="activeTab === 'data-dashboard'">
|
||||
<WorkbenchPanel v-if="canSeeWorkbenchDashboard" :roles="myRoles" :admin="isAdmin" tab="dashboard" />
|
||||
<t-empty v-else class="training-empty" description="数据驾驶舱仅人事/课长/经理可见" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'plan'">
|
||||
<PlanPanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="培训计划仅课长/经理/人事可见" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'course'">
|
||||
<CoursePanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="课程维护仅课长/经理/人事/讲师可见,学员请前往工作台课程目录" />
|
||||
<t-empty v-else class="training-empty" description="月培训计划仅课长/经理/人事/讲师可见,学员请前往培训中心课程目录" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'library'">
|
||||
<LibraryPanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="课程管理仅课长/经理/人事/讲师可见" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'sign'">
|
||||
<SignPanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
@@ -51,12 +60,14 @@
|
||||
</template>
|
||||
<StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" />
|
||||
<template v-else-if="activeTab === 'members'">
|
||||
<MemberPanel v-if="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="职称角色维护仅人事可见" />
|
||||
<!-- 职称角色对经理开放(000159):与配置中心「角色权限」页签同口径 -->
|
||||
<MemberPanel v-if="canManageConfig" />
|
||||
<t-empty v-else class="training-empty" description="职称角色维护仅人事/经理可见" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'rules'">
|
||||
<RulePanel v-if="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="配置中心仅人事可见" />
|
||||
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
|
||||
<RulePanel v-if="canManageConfig" />
|
||||
<t-empty v-else class="training-empty" description="配置中心仅人事/经理可见" />
|
||||
</template>
|
||||
<WorkbenchPanel v-else :roles="myRoles" :admin="isAdmin" :tab="workbenchTab" />
|
||||
</div>
|
||||
@@ -72,6 +83,7 @@ import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||
import WorkbenchPanel from './components/WorkbenchPanel.vue'
|
||||
import PlanPanel from './components/PlanPanel.vue'
|
||||
import CoursePanel from './components/CoursePanel.vue'
|
||||
import LibraryPanel from './components/LibraryPanel.vue'
|
||||
import SignPanel from './components/SignPanel.vue'
|
||||
import MemberPanel from './components/MemberPanel.vue'
|
||||
import StudyPanel from './components/StudyPanel.vue'
|
||||
@@ -79,10 +91,14 @@ import RulePanel from './components/RulePanel.vue'
|
||||
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
|
||||
|
||||
// 与侧栏「企业培训」分组文案一致;title 同时用于页头显示当前页签名
|
||||
// 「学习考试」已移出侧栏导航,路由保留(学习/考试状态列点击等场景仍可直达)
|
||||
const TRAINING_TABS_META: Record<string, { title: string; desc: string }> = {
|
||||
dashboard: { title: '工作台', desc: '培训运营总览、待办与达成率一览' },
|
||||
plan: { title: '培训计划', desc: '年度培训需求收集与汇总(可切换年度)' },
|
||||
course: { title: '培训课程', desc: '课程资产库、场次安排与学员名单;课件自动同步知识库' },
|
||||
dashboard: { title: '培训中心', desc: '培训运营总览、待办与达成率一览' },
|
||||
// 数据驾驶舱(000158):侧栏独立子页,内容与工作台驾驶舱视图同源
|
||||
'data-dashboard': { title: '数据驾驶舱', desc: '部门培训达成率排名、讲师积分榜与月度盘点' },
|
||||
plan: { title: '年培训计划', desc: '年度培训需求收集与汇总(可切换年度)' },
|
||||
course: { title: '月培训计划', desc: '月度培训计划排期、场次安排与学员名单;课程从课程管理选择,计划编号自动生成' },
|
||||
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
|
||||
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
|
||||
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
|
||||
members: { title: '职称角色', desc: '名册来自「组织架构」,此处维护员工职称角色' },
|
||||
@@ -117,6 +133,10 @@ const canManageTabs = computed(() =>
|
||||
isAdmin.value ||
|
||||
myRoles.value.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r)))
|
||||
|
||||
// 配置中心门槛(000158):人事/空间管理员之外,经理职称角色同权查看与维护。
|
||||
const canManageConfig = computed(() =>
|
||||
isAdmin.value || myRoles.value.some((r) => r === 'exec'))
|
||||
|
||||
// 页头角色标签:展示实际分配的角色(非权限展开),文案取自配置中心字典
|
||||
const myRoleLabel = computed(() =>
|
||||
rawRoles.value.map((r) => roleLabelOf(r, roleDict.value)).join(' / '))
|
||||
@@ -130,9 +150,9 @@ const activeTab = computed(() => {
|
||||
})
|
||||
|
||||
const activeTabMeta = computed(() => {
|
||||
// 工作台三视图:页头标题/副标题跟随当前视图(课程视图与设计稿一致使用「培训课程」)
|
||||
// 工作台三视图:页头标题/副标题跟随当前视图(课程视图「培训中心」,000154)
|
||||
if (activeTab.value === 'dashboard') {
|
||||
if (workbenchTab.value === 'course') return { title: '培训课程', desc: '课件/题库上传后自动同步知识库,可对话问答' }
|
||||
if (workbenchTab.value === 'course') return { title: '培训中心', desc: '和信课程目录、我的培训与我的考试' }
|
||||
if (workbenchTab.value === 'growth') return { title: '工作台', desc: '个人成长进阶 · 能力模型与成就任务总览' }
|
||||
return TRAINING_TABS_META.dashboard
|
||||
}
|
||||
@@ -148,12 +168,12 @@ const canSeeWorkbenchDashboard = computed(
|
||||
() => isAdmin.value || myRoles.value.some((r) => r === 'hr' || r === 'supervisor' || r === 'exec'),
|
||||
)
|
||||
|
||||
// 页头视图切换(000158):数据驾驶舱已迁侧栏独立子页,工作台仅保留课程/个人成长
|
||||
const workbenchSwitchTabs = computed(() => {
|
||||
const list: { key: WorkbenchView; label: string }[] = [
|
||||
{ key: 'course', label: '课程' },
|
||||
{ key: 'growth', label: '个人成长' },
|
||||
]
|
||||
if (canSeeWorkbenchDashboard.value) list.push({ key: 'dashboard', label: '数据驾驶舱' })
|
||||
return list
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="course-catalog">
|
||||
<!-- 工具行:范围页签(全部/线上/线下/我的课程) + 搜索 -->
|
||||
<!-- 工具行:范围页签(和信课程/我的培训/我的考试,000154) + 搜索 -->
|
||||
<div class="catalog-toolbar">
|
||||
<div class="catalog-filter" role="tablist" aria-label="课程范围">
|
||||
<button
|
||||
@@ -23,19 +23,41 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 汇总行:与设计稿一致(共 N 门 · 线上 / 线下 / 本月新增或课件数)。
|
||||
待维护 = 我主讲且「草稿」状态的课程数(2026-11 需求;>0 时用与「草稿」一致的橙色提醒)。
|
||||
待开始 = 已排期且开课时间未到的课程数(按「我的课程」口径:我主讲/我参加,2026-11 需求)。 -->
|
||||
<!-- 汇总行:随页签切换口径。
|
||||
我的培训:待维护 = 我主讲且「草稿」的课程数;待开始 = 已排期且开课时间未到的课程数。 -->
|
||||
<div class="catalog-stats">
|
||||
{{ statsText }}
|
||||
<span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span>
|
||||
<span class="catalog-stats__pending" :class="{ 'is-info': pendingStartCount > 0 }">待开始 {{ pendingStartCount }} 门</span>
|
||||
<template v-if="filter === 'mine'">
|
||||
<span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span>
|
||||
<span class="catalog-stats__pending" :class="{ 'is-info': pendingStartCount > 0 }">待开始 {{ pendingStartCount }} 门</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 课程卡片网格 -->
|
||||
<t-loading :loading="loading" class="catalog-grid-wrap">
|
||||
<!-- 我的考试:与我相关的考试记录列表(000154) -->
|
||||
<t-loading v-if="filter === 'exam'" :loading="loading" class="catalog-grid-wrap">
|
||||
<t-table :data="examRows" :columns="examColumns" row-key="id" size="small">
|
||||
<template #course_name="{ row }">{{ row.course_name || row.paper_name || '-' }}</template>
|
||||
<template #score="{ row }">
|
||||
<span :class="row.passed ? 'exam-score is-good' : 'exam-score is-bad'">{{ row.score ?? '—' }}</span>
|
||||
</template>
|
||||
<template #pass_line="{ row }">{{ row.pass_score || '-' }} / {{ row.total_score || '-' }}</template>
|
||||
<template #submitted_at="{ row }">{{ fmtExamTime(row.submitted_at) }}</template>
|
||||
</t-table>
|
||||
<t-empty v-if="!loading && !examRows.length" class="catalog-empty" description="暂无考试记录,参加随堂考试后此处展示成绩" />
|
||||
</t-loading>
|
||||
|
||||
<!-- 课程卡片网格(和信课程/我的培训) -->
|
||||
<t-loading v-else :loading="loading" class="catalog-grid-wrap">
|
||||
<div class="catalog-grid">
|
||||
<article v-for="card in visibleCards" :key="card.id" class="course-card" role="link" tabindex="0" @click="openCourse(card)" @keydown.enter="openCourse(card)">
|
||||
<article
|
||||
v-for="card in visibleCards"
|
||||
:key="card.id"
|
||||
class="course-card"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
@click="openCourse(card)"
|
||||
@keydown.enter="openCourse(card)"
|
||||
>
|
||||
<div class="course-card__cover" :class="card.mode === 'online' ? 'is-online' : 'is-offline'">
|
||||
<svg v-if="card.mode === 'online'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="12" rx="2"/><path d="m10 8.6 4 2.4-4 2.4z"/><path d="M8 21h8M12 17v4"/></svg>
|
||||
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 17.5V5a1.6 1.6 0 0 1 1.6-1.6h9A1.6 1.6 0 0 1 16.2 5v12.5"/><path d="M4 17.5A2.5 2.5 0 0 0 6.5 20h9.7"/><path d="M16.2 8.2H19a1.4 1.4 0 0 1 1.4 1.4v3.1a2.3 2.3 0 1 1-4.6 0V9.6"/><path d="M7.5 7h5M7.5 10h5"/></svg>
|
||||
@@ -46,7 +68,7 @@
|
||||
<t-tag :theme="card.mode === 'online' ? 'primary' : 'success'" variant="light" size="small" :class="{ 'course-tag-offline': card.mode !== 'online' }">
|
||||
{{ card.mode === 'online' ? '线上课程' : '线下课程' }}
|
||||
</t-tag>
|
||||
<!-- [2026-11 需求]「我的课程」角色标记:区分我要进行培训(我主讲,橙色)/ 我要参加(蓝绿色)的课程 -->
|
||||
<!-- 「我的培训」角色标记:区分我要进行培训(我主讲,橙色)/ 我要参加(蓝绿色)的课程 -->
|
||||
<t-tag
|
||||
v-if="card.roleTag"
|
||||
:theme="card.roleTag === 'teach' ? 'warning' : 'primary'"
|
||||
@@ -70,7 +92,11 @@
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<t-empty v-if="!loading && !visibleCards.length" class="catalog-empty" :description="filter === 'mine' ? '暂无与我相关的课程' : '暂无课程'" />
|
||||
<t-empty
|
||||
v-if="!loading && !visibleCards.length"
|
||||
class="catalog-empty"
|
||||
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
||||
/>
|
||||
</t-loading>
|
||||
</div>
|
||||
</template>
|
||||
@@ -81,11 +107,15 @@ import { useRouter } from 'vue-router'
|
||||
import {
|
||||
getMyProfile,
|
||||
listCourses,
|
||||
listCourseLibrary,
|
||||
listMyExamRecords,
|
||||
listMyLearningTasks,
|
||||
listSessions,
|
||||
type LearningTask,
|
||||
type MyExamRecord,
|
||||
type TrainingCourse,
|
||||
type TrainingCourseSession,
|
||||
type TrainingLibraryCourse,
|
||||
type TrainingMember,
|
||||
unwrap,
|
||||
} from '@/api/training'
|
||||
@@ -94,8 +124,10 @@ const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
||||
|
||||
const router = useRouter()
|
||||
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
|
||||
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护。
|
||||
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护;
|
||||
// 和信课程卡片为课程资产展示(000154),无学习页不跳转。
|
||||
const openCourse = (card: CatalogCard) => {
|
||||
if (card.kind === 'library') return
|
||||
if (card.unpublished) {
|
||||
goMaintain(card.id)
|
||||
return
|
||||
@@ -110,26 +142,44 @@ const goMaintain = (courseId: string) => {
|
||||
|
||||
const loading = ref(false)
|
||||
const courses = ref<TrainingCourse[]>([])
|
||||
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的课程」与待维护统计
|
||||
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计
|
||||
const lecturerCourses = ref<TrainingCourse[]>([])
|
||||
const myProfile = ref<TrainingMember | null>(null)
|
||||
const myTasks = ref<LearningTask[]>([])
|
||||
const sessions = ref<TrainingCourseSession[]>([])
|
||||
// 课程管理资产(000154):「和信课程」目录 = 课程管理已发布且部门范围覆盖查看人的课程
|
||||
const libraryItems = ref<TrainingLibraryCourse[]>([])
|
||||
// 我的考试记录(000154):「我的考试」页签数据源
|
||||
const myExamRecords = ref<MyExamRecord[]>([])
|
||||
|
||||
const FILTERS = [
|
||||
{ key: 'all', label: '全部课程' },
|
||||
{ key: 'online', label: '线上课程' },
|
||||
{ key: 'offline', label: '线下课程' },
|
||||
{ key: 'mine', label: '我的课程' },
|
||||
{ key: 'hexin', label: '和信课程' },
|
||||
{ key: 'mine', label: '我的培训' },
|
||||
{ key: 'exam', label: '我的考试' },
|
||||
] as const
|
||||
// 工作台进目录默认落在「我的课程」(2026-11 需求:与我相关的课优先展示)
|
||||
// 工作台进目录默认落在「我的培训」(与我相关的课优先展示)
|
||||
const filter = ref<string>('mine')
|
||||
const keyword = ref('')
|
||||
|
||||
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
||||
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
||||
|
||||
// 「和信课程」(000154):课程管理中已发布、且部门范围覆盖查看人的课程
|
||||
// (所属部门为空 = 全员课程;有部门则需与我的部门一致)
|
||||
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
||||
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
||||
libraryItems.value.filter(
|
||||
(c) => c.publish_status === 'published' && (!c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value),
|
||||
),
|
||||
)
|
||||
|
||||
const statsText = computed(() => {
|
||||
if (filter.value === 'exam') return `共 ${myExamRecords.value.length} 场考试`
|
||||
if (filter.value === 'hexin') {
|
||||
const list = hexinCourses.value
|
||||
const online = list.filter((c) => c.mode === 'online').length
|
||||
return `共 ${list.length} 门课程 · 线上 ${online} 门 · 线下 ${list.length - online} 门`
|
||||
}
|
||||
const list = publishedCourses.value
|
||||
const online = list.filter((c) => c.mode === 'online').length
|
||||
const offline = list.length - online
|
||||
@@ -252,27 +302,68 @@ interface CatalogCard {
|
||||
maintainable: boolean
|
||||
/** 未发布(草稿/待审)的讲师课程:无学习视角,点击直达维护 */
|
||||
unpublished: boolean
|
||||
/** [2026-11 需求]「我的课程」角色标记:teach=我主讲 / attend=我参加(其余视图不标记) */
|
||||
/** 卡片来源:plan=月计划课程(可点进学习页) / library=课程管理资产(000154,仅展示) */
|
||||
kind: 'plan' | 'library'
|
||||
/** 「我的培训」角色标记:teach=我主讲 / attend=我参加(其余视图不标记) */
|
||||
roleTag?: 'teach' | 'attend'
|
||||
}
|
||||
|
||||
// 「我的考试」表格列(000154):与我相关的考试记录
|
||||
const examColumns = [
|
||||
{ colKey: 'course_name', title: '课程/试卷' },
|
||||
{ colKey: 'score', title: '成绩', width: 90 },
|
||||
{ colKey: 'pass_line', title: '及格/总分', width: 110 },
|
||||
{ colKey: 'submitted_at', title: '交卷时间', width: 170 },
|
||||
]
|
||||
const fmtExamTime = (raw?: string | null) => {
|
||||
if (!raw) return '-'
|
||||
const d = new Date(raw)
|
||||
return Number.isNaN(d.getTime()) ? String(raw) : d.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
// 「我的考试」行数据(带搜索过滤)
|
||||
const examRows = computed<MyExamRecord[]>(() => {
|
||||
const kw = keyword.value.trim().toLowerCase()
|
||||
if (!kw) return myExamRecords.value
|
||||
return myExamRecords.value.filter(
|
||||
(r) => (r.course_name || '').toLowerCase().includes(kw) || (r.paper_name || '').toLowerCase().includes(kw),
|
||||
)
|
||||
})
|
||||
|
||||
// 卡片元信息与底部进度条:
|
||||
// 线上 = 我的学习任务状态(已完成/学习中/待学习/已逾期),进度条只表达确定状态,不虚构百分比;
|
||||
// 线下 = 真实排期进度(已完成场次/已排期场次)。
|
||||
// 未发布的讲师课程(仅「我的课程」视图可见)以草稿/待审态展示。
|
||||
// 未发布的讲师课程(仅「我的培训」视图可见)以草稿/待审态展示。
|
||||
const visibleCards = computed<CatalogCard[]>(() => {
|
||||
const kw = keyword.value.trim().toLowerCase()
|
||||
// 数据源:全部/线上/线下 = 已发布目录;我的课程 = 我相关的已发布课 + 我任讲师的课(含未发布,已发布的按 id 去重)
|
||||
// 和信课程(000154):课程管理已发布课程(资产卡片,仅展示)
|
||||
if (filter.value === 'hexin') {
|
||||
return hexinCourses.value
|
||||
.filter((c) => !kw || c.name.toLowerCase().includes(kw) || (c.category || '').toLowerCase().includes(kw))
|
||||
.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
mode: c.mode === 'online' ? 'online' : 'offline',
|
||||
meta: [c.category, c.type === 'elective' ? '选修' : '必修', c.hours ? `${c.hours} 学时` : '', c.suitable_members]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
state: '已发布',
|
||||
stateClass: 'is-good',
|
||||
barWidth: '0%',
|
||||
barClass: '',
|
||||
maintainable: false,
|
||||
unpublished: false,
|
||||
kind: 'library' as const,
|
||||
}))
|
||||
}
|
||||
// 数据源:我的培训 = 我相关的已发布课 + 我任讲师的课(含未发布,已发布的按 id 去重)
|
||||
let source = publishedCourses.value
|
||||
if (filter.value === 'mine') source = myCoursesSource.value
|
||||
let list = source.filter((c) => {
|
||||
if (filter.value === 'online' && c.mode !== 'online') return false
|
||||
if (filter.value === 'offline' && c.mode !== 'offline') return false
|
||||
if (filter.value === 'mine' && !isMyCourse(c) && !isMyTeaching(c)) return false
|
||||
if (kw && !(c.name.toLowerCase().includes(kw) || (c.tags || []).some((t) => String(t).toLowerCase().includes(kw)))) return false
|
||||
return true
|
||||
})
|
||||
// [2026-11 需求] 「我的课程」排序:需关注的课程(我主讲未发布/缺课件)置顶,
|
||||
// 「我的培训」排序:需关注的课程(我主讲未发布/缺课件)置顶,
|
||||
// 其余按与当前时间的邻近度升序(临近开课/结课的在前,无时间锚点的排最后)
|
||||
if (filter.value === 'mine') {
|
||||
const now = Date.now()
|
||||
@@ -292,7 +383,7 @@ const visibleCards = computed<CatalogCard[]>(() => {
|
||||
const head = [c.post_scope, typeText(c), `${c.hours} 学时`, c.exam_enabled ? '随堂考试' : ''].filter(Boolean).join(' · ')
|
||||
const maintainable = isMyTeaching(c) && canMaintainCourses.value
|
||||
const unpublished = c.status !== 'published'
|
||||
// [2026-11 需求]「我的课程」角色标记:我主讲(优先) / 我参加,其余视图不标记
|
||||
// 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记
|
||||
const roleTag = filter.value === 'mine' ? (isMyTeaching(c) ? ('teach' as const) : ('attend' as const)) : undefined
|
||||
// 未发布讲师课:无学习任务与排期进度,展示草稿/待审 + 计划时间(需求确认同步)
|
||||
if (unpublished) {
|
||||
@@ -308,24 +399,19 @@ const visibleCards = computed<CatalogCard[]>(() => {
|
||||
barClass: '',
|
||||
maintainable,
|
||||
unpublished,
|
||||
kind: 'plan' as const,
|
||||
roleTag,
|
||||
}
|
||||
}
|
||||
if (c.mode === 'online') {
|
||||
const task = myTaskByCourse.value.get(c.id)
|
||||
const status = task?.status || 'pending'
|
||||
const stateMap: Record<string, { state: string; cls: string }> = {
|
||||
done: { state: '已完成', cls: 'is-good' },
|
||||
doing: { state: '学习中', cls: 'is-doing' },
|
||||
overdue: { state: '已逾期', cls: 'is-bad' },
|
||||
pending: { state: '待学习', cls: '' },
|
||||
}
|
||||
const cur = status === 'done' ? { state: '已完成', cls: 'is-good', width: '100%', bar: 'is-done' }
|
||||
: status === 'doing' ? { state: '学习中', cls: 'is-doing', width: '100%', bar: 'is-doing-bar' }
|
||||
: status === 'overdue' ? { state: '已逾期', cls: 'is-bad', width: '0%', bar: '' }
|
||||
: { state: '待学习', cls: '', width: '0%', bar: '' }
|
||||
const materials = c.material_ids?.length ? ` · 课件 ${c.material_ids.length} 个` : ''
|
||||
return { id: c.id, name: c.name, mode: c.mode, meta: `${head}${materials}`, state: cur.state, stateClass: cur.cls, barWidth: cur.width, barClass: cur.bar, maintainable, unpublished, roleTag }
|
||||
return { id: c.id, name: c.name, mode: c.mode, meta: `${head}${materials}`, state: cur.state, stateClass: cur.cls, barWidth: cur.width, barClass: cur.bar, maintainable, unpublished, kind: 'plan' as const, roleTag }
|
||||
}
|
||||
const sess = (sessionByCourse.value.get(c.id) || []).sort((a, b) => String(a.start_at).localeCompare(String(b.start_at)))
|
||||
const finished = sess.filter((s) => s.status === 'finished').length
|
||||
@@ -343,6 +429,7 @@ const visibleCards = computed<CatalogCard[]>(() => {
|
||||
barClass: ratio >= 100 ? 'is-done' : '',
|
||||
maintainable,
|
||||
unpublished,
|
||||
kind: 'plan' as const,
|
||||
roleTag,
|
||||
}
|
||||
})
|
||||
@@ -352,21 +439,27 @@ const loadAll = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
// 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 id 过滤),
|
||||
// 供「我的课程」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
|
||||
// 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
|
||||
const needMaintainView = props.admin || props.roles.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r))
|
||||
const [c, t, s, me, lc] = await Promise.all([
|
||||
const [c, t, s, me, lc, lib, exams] = await Promise.all([
|
||||
// 学员目录视图:scope=student 统一走已发布课程口径(讲师账号的学习视角不受课程维护范围影响)
|
||||
listCourses({ page_size: 100, scope: 'student' }),
|
||||
listMyLearningTasks().catch(() => null),
|
||||
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
|
||||
getMyProfile().catch(() => null),
|
||||
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
|
||||
// 和信课程目录(000154):课程管理已发布课程
|
||||
listCourseLibrary({ page_size: 500 }).catch(() => null),
|
||||
// 我的考试记录(000154)
|
||||
listMyExamRecords().catch(() => null),
|
||||
])
|
||||
courses.value = unwrap(c)?.items || []
|
||||
myTasks.value = (t && unwrap(t)) || []
|
||||
sessions.value = (s && unwrap(s)) || []
|
||||
myProfile.value = (me && unwrap(me)) || null
|
||||
lecturerCourses.value = (lc && unwrap(lc)?.items) || []
|
||||
libraryItems.value = (lib && unwrap(lib)?.items) || []
|
||||
myExamRecords.value = (exams && unwrap(exams)) || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -480,6 +573,19 @@ onMounted(loadAll)
|
||||
padding: 48px 0;
|
||||
}
|
||||
|
||||
// 「我的考试」成绩列:及格绿/不及格红
|
||||
.exam-score {
|
||||
font-weight: 600;
|
||||
|
||||
&.is-good {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
&.is-bad {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
.course-card {
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -4,13 +4,16 @@
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title plan-title-row">
|
||||
年度需求收集({{ selectedYear }})
|
||||
年度需求收集
|
||||
<!-- 年份下拉用 t-option 槽渲染:TDesign :options 需 {label,value} 对象,
|
||||
直接传 number[] 会渲染空白选项(无法选中) -->
|
||||
<t-select
|
||||
v-model="selectedYear"
|
||||
class="year-select"
|
||||
:options="yearOptions"
|
||||
@change="onYearChange"
|
||||
/>
|
||||
>
|
||||
<t-option v-for="y in yearOptions" :key="y" :value="y" :label="String(y)" />
|
||||
</t-select>
|
||||
</span>
|
||||
<div class="panel-box__actions">
|
||||
<t-button v-if="canManage" theme="primary" @click="openCollect">收集下年度计划</t-button>
|
||||
@@ -18,10 +21,10 @@
|
||||
<t-button v-if="canManage" variant="outline" @click="importDemandsVisible = true">批量导入</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 搜索:状态 / 部门 / 课程名称模糊;批量确认/删除与查询条件同行 -->
|
||||
<!-- 搜索:状态 / 部门 / 课程名称模糊;批量确认(仅本部门经理)/删除与查询条件同行 -->
|
||||
<div class="demand-search">
|
||||
<t-select v-model="demandSearch.state" clearable placeholder="状态" style="width: 110px">
|
||||
<t-option label="待校验" value="pending" />
|
||||
<t-option label="待核验" value="pending" />
|
||||
<t-option label="已确认" value="confirmed" />
|
||||
<t-option label="已修正" value="fixed" />
|
||||
</t-select>
|
||||
@@ -37,7 +40,7 @@
|
||||
/>
|
||||
<t-button variant="outline" @click="loadDemands">查询</t-button>
|
||||
<t-button variant="outline" @click="onResetDemandSearch">重置</t-button>
|
||||
<t-button v-if="canManage" theme="primary" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchConfirm">批量确认</t-button>
|
||||
<t-button v-if="canConfirm" theme="primary" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchConfirm">批量确认</t-button>
|
||||
<t-button v-if="canManage" theme="danger" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchDelete">批量删除</t-button>
|
||||
<span class="demand-selected-hint">已选 {{ selectedDemandKeys.length }} 项(可批量确认/删除未确认需求)</span>
|
||||
</div>
|
||||
@@ -50,10 +53,17 @@
|
||||
:loading="loading"
|
||||
>
|
||||
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
||||
<template #code="{ row }">
|
||||
<t-tooltip v-if="row.code" :content="row.code">
|
||||
<span class="cell-ellipsis">{{ row.code }}</span>
|
||||
</t-tooltip>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<template #lecturer_name="{ row }">{{ row.lecturer_name || '-' }}</template>
|
||||
<template #planned_time="{ row }">{{ (row.planned_time || '').slice(0, 10) || '-' }}</template>
|
||||
<!-- 计划培训月份入库格式「YYYY-M」(如 2027-1),原样展示 -->
|
||||
<template #planned_time="{ row }">{{ row.planned_time || '-' }}</template>
|
||||
<template #location="{ row }">{{ row.location || '-' }}</template>
|
||||
<!-- 参加人员/备注可能很长:单行省略,悬停浮出全部内容 -->
|
||||
<!-- 适合人员/备注可能很长:单行省略,悬停浮出全部内容 -->
|
||||
<template #post_scope="{ row }">
|
||||
<t-tooltip v-if="row.post_scope" :content="row.post_scope">
|
||||
<span class="cell-ellipsis">{{ row.post_scope }}</span>
|
||||
@@ -68,13 +78,13 @@
|
||||
</template>
|
||||
<template #check_status="{ row }">
|
||||
<t-tag v-if="row.check_status === 'passed'" theme="success" variant="light" size="small">已确认</t-tag>
|
||||
<t-tag v-else-if="row.check_status === 'pending'" theme="warning" variant="light" size="small">待校验</t-tag>
|
||||
<t-tag v-else-if="row.check_status === 'pending'" theme="warning" variant="light" size="small">待核验</t-tag>
|
||||
<t-tag v-else theme="default" variant="light" size="small">已修正</t-tag>
|
||||
</template>
|
||||
<template #op="{ row }">
|
||||
<template v-if="row.status !== 'confirmed'">
|
||||
<t-button
|
||||
v-if="canManage"
|
||||
v-if="canConfirm"
|
||||
variant="text" theme="primary" size="small" @click="onConfirmDemand(row)"
|
||||
>确认</t-button>
|
||||
<t-button
|
||||
@@ -91,30 +101,54 @@
|
||||
<!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) -->
|
||||
<t-dialog v-model:visible="demandFormVisible" :header="demandDialogTitle" width="560">
|
||||
<t-form :data="demandForm" label-width="90" @submit="onSaveDemand">
|
||||
<t-form-item v-if="demandForm.id" label="编号" name="code">
|
||||
<t-input :value="demandCodeDisplay" disabled />
|
||||
</t-form-item>
|
||||
<t-form-item label="课程名称" name="course_name" required>
|
||||
<t-input v-model="demandForm.course_name" placeholder="请输入课程名称" />
|
||||
<!-- 000156:从课程管理选择本部门课程(自动带出分类/讲师/适合人员),也可直接填写新课程 -->
|
||||
<t-select
|
||||
v-model="demandForm.course_name"
|
||||
clearable
|
||||
filterable
|
||||
creatable
|
||||
:loading="libraryLoading"
|
||||
placeholder="从课程管理选择本部门课程,或直接填写新课程"
|
||||
style="width: 100%"
|
||||
@change="onDemandCourseChange"
|
||||
>
|
||||
<t-option
|
||||
v-for="c in deptCourseOptions"
|
||||
:key="c.id"
|
||||
:value="c.name"
|
||||
:label="`${c.name}${c.category ? `(${c.category})` : ''}`"
|
||||
/>
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item label="分类" name="category">
|
||||
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
|
||||
</t-form-item>
|
||||
<t-form-item label="所属部门" name="dept_id">
|
||||
<t-input :value="deptDisplay" disabled placeholder="提交时按提报人所在部门自动获取" />
|
||||
</t-form-item>
|
||||
<t-form-item label="参加人员" name="post_scope">
|
||||
<t-input v-model="demandForm.post_scope" placeholder="可填写多个参加人员,用、或,分隔(选填)" />
|
||||
<t-form-item label="适合人员" name="post_scope">
|
||||
<t-input v-model="demandForm.post_scope" placeholder="可填写多个适合人员,用、或,分隔(选填)" />
|
||||
</t-form-item>
|
||||
<t-form-item label="计划培训时间" name="planned_time">
|
||||
<t-date-picker
|
||||
v-model="demandForm.planned_time"
|
||||
format="YYYY-MM-DD"
|
||||
<t-form-item label="计划培训月份" name="planned_month">
|
||||
<t-select
|
||||
v-model="demandForm.planned_month"
|
||||
clearable
|
||||
placeholder="选填,精确到日期;确认后同步到培训课程"
|
||||
placeholder="选填,只需选到月份;确认后同步到培训课程"
|
||||
style="width: 100%"
|
||||
/>
|
||||
>
|
||||
<t-option v-for="m in 12" :key="m" :label="`${m} 月`" :value="m" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item label="内/外培训" name="train_type">
|
||||
<t-radio-group v-model="demandForm.train_type" variant="default-filled">
|
||||
<t-radio-button value="">未选择</t-radio-button>
|
||||
<t-radio-button value="内部">内部</t-radio-button>
|
||||
<t-radio-button value="外部">外部</t-radio-button>
|
||||
</t-radio-group>
|
||||
<!-- 下拉选择(000154):内部/外部,清空即未选择 -->
|
||||
<t-select v-model="demandForm.train_type" clearable placeholder="从下拉选择内部或外部(选填)" style="width: 100%">
|
||||
<t-option label="内部" value="内部" />
|
||||
<t-option label="外部" value="外部" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item label="厂区" name="plant">
|
||||
<t-input v-model="demandForm.plant" placeholder="如:三厂(选填)" />
|
||||
@@ -158,15 +192,15 @@
|
||||
<t-textarea
|
||||
v-model="importDemandsText"
|
||||
:autosize="{ minRows: 6 }"
|
||||
placeholder="或粘贴需求行:课程名称[,计划培训时间如 2026-11-19] (支持中英文逗号)"
|
||||
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
|
||||
/>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓(内部或外部)/计划培训时间(如 2026-11-19)/讲师/备注;参加人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;未指定部门的需求导入后为「待校验」,由人事确认补全。</div>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/培訓費用/内/外培训(内部或外部,下拉选择)/计划培训月份(1~12,下拉选择)/讲师/备注;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- 收集下年度计划:发送模板 + 推送人员(默认人事与各课长,可增删),确认后站内+企微批量推送 -->
|
||||
<!-- 收集下年度计划:发送模板 + 推送人员(默认各课长,可增删),确认后站内+企微批量推送 -->
|
||||
<t-dialog v-model:visible="collectVisible" :header="`收集下年度计划(${nextYear})`" width="560">
|
||||
<div class="collect-section-title">发送模板</div>
|
||||
<div class="collect-template-row">
|
||||
@@ -179,13 +213,13 @@
|
||||
multiple
|
||||
filterable
|
||||
clearable
|
||||
placeholder="默认各部门经理、主管、文员,可修改添加删除"
|
||||
placeholder="默认各课长,可修改添加删除"
|
||||
style="width: 100%"
|
||||
:loading="membersLoading"
|
||||
>
|
||||
<t-option v-for="m in members" :key="m.user_id" :value="m.user_id" :label="memberLabel(m)" />
|
||||
</t-select>
|
||||
<div class="form-hint">默认勾选各部门经理、主管、文员;可自行添加或移除推送人员。</div>
|
||||
<div class="form-hint">默认勾选各课长;可自行添加或移除推送人员。</div>
|
||||
<div class="collect-section-title">通知内容</div>
|
||||
<t-textarea v-model="collectForm.content" :autosize="{ minRows: 3 }" />
|
||||
<template #footer>
|
||||
@@ -208,6 +242,8 @@ import {
|
||||
deleteDemand,
|
||||
getMyProfile,
|
||||
importDemands,
|
||||
listCourseLibrary,
|
||||
listDemandYears,
|
||||
listDemands,
|
||||
listDepts,
|
||||
listLecturers,
|
||||
@@ -215,6 +251,7 @@ import {
|
||||
saveDemand,
|
||||
type TrainingDept,
|
||||
type TrainingDemand,
|
||||
type TrainingLibraryCourse,
|
||||
type TrainingLecturerOption,
|
||||
type TrainingMember,
|
||||
unwrap,
|
||||
@@ -224,35 +261,59 @@ const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
||||
|
||||
// 计划管理(录入/推送/排课):人事/课长(roles 已按权限组展开,经理自动命中课长)
|
||||
const canManage = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor'))
|
||||
// 核验确认入口:经理职称角色可见(空间管理员直通,便于授权引导);
|
||||
// 实际可确认范围按行校验(本部门+经理,000154),越权点击统一提示联系部门经理。
|
||||
const canConfirm = computed(() => props.admin || props.roles.some((r) => r === 'exec'))
|
||||
// 行级确认权限:需求归属部门=本人所在部门,且本人具有经理职称角色。
|
||||
const canConfirmDemand = (row: TrainingDemand) =>
|
||||
canConfirm.value && Boolean(row.dept_id) && row.dept_id === myDeptId.value
|
||||
|
||||
const now = new Date()
|
||||
const currentYear = now.getFullYear()
|
||||
|
||||
// 年度需求收集:可切换年度查看各年的收集汇总(近 4 年 + 明年)
|
||||
// 年度需求收集:年份下拉为需求库实际年份(降序),默认展示最新一年(无数据回退当前年)
|
||||
const selectedYear = ref(currentYear)
|
||||
const yearOptions = Array.from({ length: 6 }, (_, i) => currentYear - 4 + i)
|
||||
const yearOptions = ref<number[]>([])
|
||||
const onYearChange = () => loadDemands()
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const demands = ref<TrainingDemand[]>([])
|
||||
|
||||
// 表单/搜索数据源:部门树、讲师名册
|
||||
// 表单/搜索数据源:部门树、讲师名册、课程管理条目(课程名称下拉,000156)
|
||||
const depts = ref<TrainingDept[]>([])
|
||||
const lecturers = ref<TrainingLecturerOption[]>([])
|
||||
const libraryCourses = ref<TrainingLibraryCourse[]>([])
|
||||
const libraryLoading = ref(false)
|
||||
const myDeptName = ref('')
|
||||
// 本人所在部门 id:行级确认权限校验用(需求归属部门须与本人一致)
|
||||
const myDeptId = ref('')
|
||||
|
||||
// 本部门课程(000156):课程名称下拉仅列所属部门课程——新建按提报人部门,
|
||||
// 编辑按需求归属部门(人事代改他部门需求时同样联动);部门为空回退全部课程
|
||||
const deptCourseOptions = computed(() => {
|
||||
const deptId = demandForm.value.id
|
||||
? demands.value.find((d) => d.id === demandForm.value.id)?.dept_id || myDeptId.value
|
||||
: myDeptId.value
|
||||
return deptId
|
||||
? libraryCourses.value.filter((c) => c.owner_dept_id === deptId)
|
||||
: libraryCourses.value
|
||||
})
|
||||
|
||||
const demandFormVisible = ref(false)
|
||||
const importDemandsVisible = ref(false)
|
||||
const importDemandsText = ref('')
|
||||
|
||||
// 搜索条件:已确认按人工确认(status)过滤,待校验/已修正按规则校验状态(check_status)
|
||||
// 搜索条件:已确认按人工确认(status)过滤,待核验/已修正按规则校验状态(check_status)
|
||||
const demandSearch = ref({ state: '', dept_id: '', keyword: '' })
|
||||
|
||||
const demandForm = ref({
|
||||
id: '',
|
||||
course_name: '',
|
||||
planned_time: '',
|
||||
// 分类随所选课程自动带出(000156),确认后经需求→课程同步落到课程侧标签
|
||||
category: '',
|
||||
// 计划培训月份(1~12,选填):提交时与收集年度合成 planned_time「YYYY-M」
|
||||
planned_month: '' as '' | number,
|
||||
session_count: 1,
|
||||
train_type: '',
|
||||
plant: '',
|
||||
@@ -263,6 +324,22 @@ const demandForm = ref({
|
||||
remark: '',
|
||||
})
|
||||
|
||||
// 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改;
|
||||
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
|
||||
const onDemandCourseChange = (name: unknown) => {
|
||||
const course = libraryCourses.value.find((c) => c.name === name)
|
||||
if (!course) return
|
||||
demandForm.value.category = course.category || ''
|
||||
if (course.suitable_members) demandForm.value.post_scope = course.suitable_members
|
||||
const lecturerValue = course.lecturer_id || course.lecturer_external || ''
|
||||
if (lecturerValue) {
|
||||
if (!lecturers.value.some((l) => l.id === lecturerValue)) {
|
||||
lecturers.value = [...lecturers.value, { id: lecturerValue, name: course.lecturer_name || lecturerValue }]
|
||||
}
|
||||
demandForm.value.lecturer = lecturerValue
|
||||
}
|
||||
}
|
||||
|
||||
// 讲师解析:名册 id 直接用;名册姓名映射为对应 id;否则作为外部讲师姓名落 lecturer_external
|
||||
const resolveLecturer = (value: string): { lecturer_id: string; lecturer_external: string } => {
|
||||
const v = (value || '').trim()
|
||||
@@ -275,6 +352,12 @@ const resolveLecturer = (value: string): { lecturer_id: string; lecturer_externa
|
||||
|
||||
const demandDialogTitle = computed(() => (demandForm.value.id ? '编辑培训需求' : '在线提报培训需求'))
|
||||
|
||||
// 编辑态展示年计划编号(服务端生成,不可改)
|
||||
const demandCodeDisplay = computed(() => {
|
||||
const row = demands.value.find((d) => d.id === demandForm.value.id)
|
||||
return row?.code || '-'
|
||||
})
|
||||
|
||||
const deptMap = computed(() => {
|
||||
const m: Record<string, string> = {}
|
||||
for (const d of depts.value) m[d.id] = d.name
|
||||
@@ -292,11 +375,13 @@ const deptDisplay = computed(() => {
|
||||
|
||||
const demandColumns = [
|
||||
{ colKey: 'row-select', type: 'multiple', width: 44, disabled: ({ row }: { row: TrainingDemand }) => row.status === 'confirmed' },
|
||||
// 年计划编号(AP-<year>-####,创建时由服务端生成)
|
||||
{ colKey: 'code', title: '编号', width: 130 },
|
||||
{ colKey: 'course_name', title: '课程名称' },
|
||||
{ colKey: 'dept_name', title: '部门', width: 100 },
|
||||
{ colKey: 'post_scope', title: '参加人员', width: 140 },
|
||||
{ colKey: 'post_scope', title: '适合人员', width: 140 },
|
||||
{ colKey: 'lecturer_name', title: '讲师', width: 100 },
|
||||
{ colKey: 'planned_time', title: '计划培训时间', width: 110 },
|
||||
{ colKey: 'planned_time', title: '计划培训月份', width: 110 },
|
||||
{ colKey: 'train_type', title: '内/外培训', width: 90 },
|
||||
{ colKey: 'location', title: '地点', width: 100 },
|
||||
{ colKey: 'remark', title: '备注', minWidth: 140 },
|
||||
@@ -315,11 +400,17 @@ const onBatchConfirm = async () => {
|
||||
MessagePlugin.warning('请先勾选未确认的需求')
|
||||
return
|
||||
}
|
||||
// 000154:批量确认仅作用于本人可确认的需求(本部门+经理),越权行全部跳过
|
||||
const allowed = rows.filter(canConfirmDemand)
|
||||
if (!allowed.length) {
|
||||
MessagePlugin.warning('暂无权限,请联系部门经理~')
|
||||
return
|
||||
}
|
||||
batchSaving.value = true
|
||||
let ok = 0
|
||||
let fail = 0
|
||||
try {
|
||||
for (const row of rows) {
|
||||
for (const row of allowed) {
|
||||
try {
|
||||
await confirmDemand(row.id)
|
||||
ok += 1
|
||||
@@ -327,7 +418,11 @@ const onBatchConfirm = async () => {
|
||||
fail += 1
|
||||
}
|
||||
}
|
||||
MessagePlugin.success(`批量确认完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''};已确认需求已自动生成草稿课程到培训课程`)
|
||||
const skipped = rows.length - allowed.length
|
||||
MessagePlugin.success(
|
||||
`批量确认完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''}` +
|
||||
`${skipped ? `,跳过 ${skipped} 条非本部门需求` : ''};已确认需求已自动生成草稿课程到培训课程`,
|
||||
)
|
||||
selectedDemandKeys.value = []
|
||||
loadAll()
|
||||
} finally {
|
||||
@@ -378,6 +473,20 @@ const loadDemands = async () => {
|
||||
demands.value = unwrap(d)?.items || []
|
||||
}
|
||||
|
||||
// 年份下拉数据源:需求库实际年份(降序)。resetSelection=true 时默认选中最新一年
|
||||
// (首次进入);后续刷新仅在当前选中年份已无数据时回退最新,避免打断用户选择。
|
||||
const loadDemandYears = async (resetSelection = false) => {
|
||||
try {
|
||||
const years = unwrap<number[]>(await listDemandYears()) || []
|
||||
yearOptions.value = years
|
||||
if (years.length && (resetSelection || !years.includes(selectedYear.value))) {
|
||||
selectedYear.value = years[0]
|
||||
}
|
||||
} catch {
|
||||
/* 年份拉取失败保留当前选择,列表按当前年份照常查询 */
|
||||
}
|
||||
}
|
||||
|
||||
const onResetDemandSearch = () => {
|
||||
demandSearch.value = { state: '', dept_id: '', keyword: '' }
|
||||
loadDemands()
|
||||
@@ -385,20 +494,33 @@ const onResetDemandSearch = () => {
|
||||
|
||||
// 表单下拉与提报人部门(一次性加载,失败不阻塞主列表)
|
||||
const loadFormOptions = async () => {
|
||||
libraryLoading.value = true
|
||||
try {
|
||||
const [d, l, me] = await Promise.all([listDepts(), listLecturers(), getMyProfile()])
|
||||
const [d, l, me, lib] = await Promise.all([
|
||||
listDepts(),
|
||||
listLecturers(),
|
||||
getMyProfile(),
|
||||
listCourseLibrary({ page_size: 500 }).catch(() => null),
|
||||
])
|
||||
depts.value = unwrap(d) || []
|
||||
lecturers.value = unwrap(l) || []
|
||||
libraryCourses.value = (lib && unwrap(lib))?.items || []
|
||||
const member = unwrap(me)
|
||||
if (member?.dept_id) myDeptName.value = deptMap.value[member.dept_id] || ''
|
||||
if (member?.dept_id) {
|
||||
myDeptId.value = member.dept_id
|
||||
myDeptName.value = deptMap.value[member.dept_id] || ''
|
||||
}
|
||||
} catch {
|
||||
/* 忽略:仅影响下拉可选项 */
|
||||
} finally {
|
||||
libraryLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const loadAll = async () => {
|
||||
const loadAll = async (resetYearSelection = false) => {
|
||||
loading.value = true
|
||||
try {
|
||||
await loadDemandYears(resetYearSelection)
|
||||
await loadDemands()
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -409,7 +531,8 @@ const onOpenDemandForm = () => {
|
||||
demandForm.value = {
|
||||
id: '',
|
||||
course_name: '',
|
||||
planned_time: '',
|
||||
category: '',
|
||||
planned_month: '',
|
||||
session_count: 1,
|
||||
train_type: '',
|
||||
plant: '',
|
||||
@@ -421,16 +544,31 @@ const onOpenDemandForm = () => {
|
||||
demandFormVisible.value = true
|
||||
}
|
||||
|
||||
// 计划培训月份回显:从「YYYY-M」取月份;旧日期格式(YYYY-MM-DD)无法映射月份留空
|
||||
const plannedMonthOfValue = (value: string): '' | number => {
|
||||
const m = (value || '').trim().match(/^\d{4}-(\d{1,2})$/)
|
||||
const month = m ? Number(m[1]) : 0
|
||||
return month >= 1 && month <= 12 ? month : ''
|
||||
}
|
||||
|
||||
// 编辑旧数据兜底:原计划培训时间为旧日期格式且未重新选择月份时,保存保留原值
|
||||
const editOriginalPlanned = ref({ planned_time: '', expect_month: 0 })
|
||||
|
||||
const onEditDemand = (row: TrainingDemand) => {
|
||||
// 讲师回显:系统员工(id)或外部姓名;不在名册的值追加临时选项避免显示裸 ID
|
||||
const lecturerValue = row.lecturer_id || row.lecturer_external || ''
|
||||
if (lecturerValue && !lecturers.value.some((l) => l.id === lecturerValue)) {
|
||||
lecturers.value = [...lecturers.value, { id: lecturerValue, name: row.lecturer_name || lecturerValue }]
|
||||
}
|
||||
editOriginalPlanned.value = {
|
||||
planned_time: row.planned_time || '',
|
||||
expect_month: row.expect_month || 0,
|
||||
}
|
||||
demandForm.value = {
|
||||
id: row.id,
|
||||
course_name: row.course_name,
|
||||
planned_time: row.planned_time || '',
|
||||
category: row.category || '',
|
||||
planned_month: plannedMonthOfValue(row.planned_time || ''),
|
||||
session_count: row.session_count || 1,
|
||||
train_type: row.train_type || '',
|
||||
plant: row.plant || '',
|
||||
@@ -449,15 +587,21 @@ const onSaveDemand = async () => {
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
// 计划培训时间只保留年月日入库;讲师解析为 id 或外部姓名
|
||||
const { lecturer, ...rest } = demandForm.value
|
||||
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
|
||||
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名
|
||||
const { lecturer, planned_month, ...rest } = demandForm.value
|
||||
const month = Number(planned_month) || 0
|
||||
const isEdit = Boolean(demandForm.value.id)
|
||||
await saveDemand({
|
||||
...rest,
|
||||
...resolveLecturer(lecturer),
|
||||
planned_time: plannedTimeOf(demandForm.value.planned_time),
|
||||
planned_time: month
|
||||
? `${selectedYear.value}-${month}`
|
||||
: (isEdit ? editOriginalPlanned.value.planned_time : ''),
|
||||
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
|
||||
year: selectedYear.value,
|
||||
})
|
||||
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待人事确认')
|
||||
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待核验')
|
||||
demandFormVisible.value = false
|
||||
loadAll()
|
||||
} catch (e: any) {
|
||||
@@ -486,17 +630,19 @@ const onImportDemands = async () => {
|
||||
const items: Partial<TrainingDemand>[] = []
|
||||
const skipped: string[] = []
|
||||
lines.forEach((line, idx) => {
|
||||
// 兼容中英文逗号(\uFF0C)与制表符拆分:课程名称[,计划培训时间]
|
||||
// 兼容中英文逗号(\uFF0C)与制表符拆分:课程名称[,计划培训月份]
|
||||
const parts = line.split(/[,\uFF0C\t]/).map((s) => s.trim())
|
||||
const courseName = parts[0] || ''
|
||||
if (!courseName) {
|
||||
skipped.push(String(idx + 1))
|
||||
return
|
||||
}
|
||||
const { planned, month } = plannedMonthFromValue(parts[1] || '', selectedYear.value)
|
||||
items.push({
|
||||
course_name: courseName,
|
||||
year: selectedYear.value,
|
||||
planned_time: plannedTimeFromRow({ v: parts[1] || '' }, 'v', selectedYear.value) || undefined,
|
||||
planned_time: planned || undefined,
|
||||
expect_month: month || undefined,
|
||||
})
|
||||
})
|
||||
if (!items.length) {
|
||||
@@ -519,41 +665,34 @@ const onImportDemands = async () => {
|
||||
}
|
||||
|
||||
// ---- 教育训练需求表模板导入(docs/moban,经 /templates/ 下发) ----
|
||||
// 模板表头:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓/计划培训时间/讲师/备注,
|
||||
// 讲师按员工档案姓名匹配(带出部门)、非系统员工落外部讲师姓名,计划培训时间只保留年月日。
|
||||
// 模板表头:编号/部门/课程名称/适合人员/地点/培訓費用/内/外培训/计划培训月份(1~12)/讲师/备注,
|
||||
// 讲师按员工档案姓名匹配(带出部门)、非系统员工落外部讲师姓名,计划培训月份按「收集年度-月份」入库。
|
||||
|
||||
const onDownloadDemandTemplate = () => downloadTrainingTemplate(DEMAND_TEMPLATE_KEY)
|
||||
|
||||
// 计划培训时间入库格式:只保留年月日(YYYY-MM-DD)
|
||||
const plannedTimeOf = (value: string) => (value || '').trim().slice(0, 10)
|
||||
|
||||
// 从模板 Excel「计划培训时间」列解析计划培训时间:兼容 2026/6/8、2026-6-8、
|
||||
// 2026年6月8日、6/8(年份缺省取当前收集年度)及"11"这类纯月份(归一到当月 1 日);
|
||||
// 尾随时分忽略(入库只到日);越界或解析失败返回空串
|
||||
const plannedTimeFromRow = (row: Record<string, string>, timeCol: string, fallbackYear: number): string => {
|
||||
const raw = (row[timeCol] || '').trim()
|
||||
if (!raw) return ''
|
||||
const pad = (n: string) => n.padStart(2, '0')
|
||||
const validDate = (m: string, d: string) => {
|
||||
const month = Number(m)
|
||||
const day = Number(d)
|
||||
return month >= 1 && month <= 12 && day >= 1 && day <= 31
|
||||
// 计划培训月份解析:兼容 1~12 纯月份数字(1、12月)与旧日期格式(2027-1、
|
||||
// 2026/6/8、2026年6月8日等取其月份);年份统一取收集年度(模板标题年),
|
||||
// 入库 planned_time=「YYYY-M」(如 2027-1);无法解析返回空。
|
||||
const plannedMonthFromValue = (raw: string, fallbackYear: number): { planned: string; month: number } => {
|
||||
const v = (raw || '').trim()
|
||||
if (!v) return { planned: '', month: 0 }
|
||||
const full = v.match(/^20\d{2}[-/.年]\s*(\d{1,2})/)
|
||||
if (full) {
|
||||
const month = Number(full[1])
|
||||
if (month >= 1 && month <= 12) return { planned: `${fallbackYear}-${month}`, month }
|
||||
}
|
||||
const full = raw.match(/(\d{4})[./\-\s年]*(\d{1,2})[./\-\s月]*(\d{1,2})日?/)
|
||||
if (full && validDate(full[2], full[3])) {
|
||||
return `${full[1]}-${pad(full[2])}-${pad(full[3])}`
|
||||
const monthOnly = v.match(/^(\d{1,2})\s*月?$/)
|
||||
if (monthOnly) {
|
||||
const month = Number(monthOnly[1])
|
||||
if (month >= 1 && month <= 12) return { planned: `${fallbackYear}-${month}`, month }
|
||||
}
|
||||
const short = raw.match(/(\d{1,2})[./月](\d{1,2})日?/)
|
||||
if (short && validDate(short[1], short[2])) {
|
||||
return `${fallbackYear}-${pad(short[1])}-${pad(short[2])}`
|
||||
}
|
||||
const monthOnly = raw.match(/^(\d{1,2})\s*月?$/)
|
||||
if (monthOnly && Number(monthOnly[1]) >= 1 && Number(monthOnly[1]) <= 12) {
|
||||
return `${fallbackYear}-${pad(monthOnly[1])}-01`
|
||||
}
|
||||
return ''
|
||||
return { planned: '', month: 0 }
|
||||
}
|
||||
|
||||
// 模板 Excel 列取值:新「计划培训月份」列优先,兼容旧「计划培训时间」列模板
|
||||
const plannedMonthFromRow = (row: Record<string, string>, fallbackYear: number) =>
|
||||
plannedMonthFromValue((row['计划培训月份'] || row['计划培训时间'] || '').trim(), fallbackYear)
|
||||
|
||||
const onImportDemandExcel = async (e: Event) => {
|
||||
const input = e.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
@@ -564,10 +703,21 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
// 定位含「课程名称」表头的工作表(模板首两行为公司/表题合并单元格);
|
||||
// 表头键做空白归一(兼容「地 点」等内含空格的列名,否则该列会被静默丢弃)
|
||||
let dataRows: Record<string, string>[] | null = null
|
||||
// 模板标题年(000157):标题行「2027 年度教育训练需求表」的年份优先于年份下拉——
|
||||
// 模板面向下一年度收集,导入按标题年入库(需求年份与计划培训「年-月」一致)
|
||||
let titleYear = selectedYear.value
|
||||
for (const name of wb.SheetNames) {
|
||||
const sheetRows = XLSX.utils.sheet_to_json<string[]>(wb.Sheets[name], { header: 1, raw: false, defval: '' })
|
||||
const headerIdx = sheetRows.findIndex((r) => r.some((c) => String(c).trim() === '课程名称'))
|
||||
if (headerIdx < 0) continue
|
||||
for (const r of sheetRows.slice(0, Math.max(headerIdx, 1))) {
|
||||
const hit = (r || []).map((c) => String(c)).find((s) => /20\d{2}/.test(s) && s.includes('年'))
|
||||
const m = hit?.match(/20\d{2}/)
|
||||
if (m) {
|
||||
titleYear = Number(m[0])
|
||||
break
|
||||
}
|
||||
}
|
||||
const header = (sheetRows[headerIdx] || []).map((c) => String(c).trim().replace(/\s+/g, ''))
|
||||
dataRows = sheetRows.slice(headerIdx + 1).map((arr) => {
|
||||
const row: Record<string, string> = {}
|
||||
@@ -638,18 +788,22 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
externalLecturers += 1
|
||||
}
|
||||
}
|
||||
// 计划培训月份:新「计划培训月份」列(1~12)优先,兼容旧「计划培训时间」列;
|
||||
// 年份取模板标题年(000157),入库「YYYY-M」并回填期望月份
|
||||
const plannedMonth = plannedMonthFromRow(row, titleYear)
|
||||
items.push({
|
||||
course_name: courseName,
|
||||
year: selectedYear.value,
|
||||
year: titleYear,
|
||||
plant: (row['厂区'] || '').trim(),
|
||||
session_count: Number.parseInt(row['次数'] || '') || 1,
|
||||
location: (row['地点'] || '').trim(),
|
||||
post_scope: (row['参加人员'] || '').trim(),
|
||||
train_type: (row['內/外培訓'] || row['内/外培训'] || '').trim(),
|
||||
post_scope: (row['适合人员'] || row['参加人员'] || '').trim(),
|
||||
train_type: (row['内/外培训'] || row['內/外培訓'] || '').trim(),
|
||||
lecturer_id: lecturerId,
|
||||
lecturer_external: lecturerExternal || undefined,
|
||||
dept_id: deptId,
|
||||
planned_time: plannedTimeFromRow(row, '计划培训时间', selectedYear.value) || undefined,
|
||||
planned_time: plannedMonth.planned || undefined,
|
||||
expect_month: plannedMonth.month || undefined,
|
||||
remark: (row['备注'] || '').trim(),
|
||||
})
|
||||
})
|
||||
@@ -659,16 +813,19 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
await importDemands(items)
|
||||
const imported = unwrap(await importDemands(items)) as { imported: number; notified?: number } | null
|
||||
MessagePlugin.success(
|
||||
`已从模板导入 ${items.length} 条需求` +
|
||||
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
|
||||
(lecturerHits || externalLecturers
|
||||
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
|
||||
: '') +
|
||||
(deptFromLecturer ? `(其中 ${deptFromLecturer} 条部门按讲师带出)` : '') +
|
||||
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : ''),
|
||||
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
|
||||
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
|
||||
)
|
||||
importDemandsVisible.value = false
|
||||
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
|
||||
if (titleYear !== selectedYear.value) selectedYear.value = titleYear
|
||||
loadAll()
|
||||
} catch {
|
||||
MessagePlugin.error('导入失败,请稍后重试')
|
||||
@@ -681,6 +838,11 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
}
|
||||
|
||||
const onConfirmDemand = async (row: TrainingDemand) => {
|
||||
// 000154:仅需求归属部门的经理可确认,其余人员点击统一提示
|
||||
if (!canConfirmDemand(row)) {
|
||||
MessagePlugin.warning('暂无权限,请联系部门经理~')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await confirmDemand(row.id)
|
||||
MessagePlugin.success('已确认,草稿课程已自动生成到培训课程')
|
||||
@@ -702,11 +864,13 @@ const collectForm = ref({ userIds: [] as string[], content: '' })
|
||||
const memberLabel = (m: TrainingMember) =>
|
||||
[m.user_name || m.employee_no, m.post, m.dept_name].filter(Boolean).join(' · ') || m.id.slice(0, 8)
|
||||
|
||||
// 默认推送人员:人事与各课长(supervisor;存量文员经别名按课长对待)
|
||||
const DEFAULT_COLLECT_ROLES = ['hr', 'supervisor']
|
||||
// 默认推送人员:各课长(supervisor;存量文员 clerk 经别名按课长对待)
|
||||
const DEFAULT_COLLECT_ROLES = ['supervisor']
|
||||
const defaultCollectUserIds = () =>
|
||||
members.value
|
||||
.filter((m) => (m.roles || []).some((r) => DEFAULT_COLLECT_ROLES.includes(r)))
|
||||
.filter((m) =>
|
||||
(m.roles || []).some((r) => DEFAULT_COLLECT_ROLES.includes(r === 'clerk' ? 'supervisor' : r)),
|
||||
)
|
||||
.map((m) => m.user_id)
|
||||
|
||||
const openCollect = async () => {
|
||||
@@ -754,7 +918,8 @@ const onSendCollect = async () => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadAll()
|
||||
// 首次进入:年份默认选中需求库最新一年并展示该年数据
|
||||
loadAll(true)
|
||||
loadFormOptions()
|
||||
})
|
||||
</script>
|
||||
@@ -770,6 +935,12 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
// 已确认行不做整行置灰:t-table 行选择列 disabled 命中时会加 __row--disabled
|
||||
// 类(整行 text-color-disabled),业务上已确认行仅禁止勾选,文字保持正常色
|
||||
:deep(.t-table__row--disabled) {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
// 标题行内嵌年度切换下拉
|
||||
.plan-title-row {
|
||||
display: inline-flex;
|
||||
@@ -842,7 +1013,7 @@ onMounted(() => {
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
// 参加人员/备注等长文本单元格:单行省略,t-tooltip 悬停显示全部
|
||||
// 适合人员/备注等长文本单元格:单行省略,t-tooltip 悬停显示全部
|
||||
.cell-ellipsis {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
<template>
|
||||
<div class="rule-panel">
|
||||
<!-- 卡片1:职称角色 · 角色与权限(点选式维护,自定义角色勾选权限分配即生效) -->
|
||||
<!-- [2026-11 需求] 配置中心 tab 化:角色权限/业务规则(含业务参数与课程分类)/推送管理(推送提醒配置+推送记录)/导入模板 -->
|
||||
<t-tabs v-model="activeTab" class="rule-tabs">
|
||||
<t-tab-panel value="roles" label="角色权限">
|
||||
<!-- 角色权限 · 角色与权限(点选式维护,自定义角色勾选权限分配即生效) -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">职称角色 · 角色与权限</span>
|
||||
<span class="panel-box__title">角色权限 · 角色与权限</span>
|
||||
<t-button variant="outline" size="small" @click="openRoleDialog()">新增角色</t-button>
|
||||
</div>
|
||||
<t-table :data="roleRows" :columns="roleColumns" row-key="key" size="small" :loading="roleLoading">
|
||||
@@ -40,15 +43,18 @@
|
||||
系统角色不可删除,展示名与权限分配可改;「权限分配」= 继承所选权限组的全部接口与页面权限,勾选多个取并集。学员为全员默认角色,无需配置。
|
||||
</div>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
|
||||
<!-- 卡片2:业务规则(全部点选式表单,不再手写 JSON) -->
|
||||
<!-- 业务规则:签到/评分/积分/达标线/滚动等业务规则与业务参数 + 课程分类字典 + 高级配置兜底 -->
|
||||
<t-tab-panel value="rules" label="业务规则">
|
||||
<!-- 业务规则(全部点选式表单,不再手写 JSON) -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">业务规则</span>
|
||||
<t-button variant="outline" size="small" :loading="seeding" @click="onSeed">初始化默认配置</t-button>
|
||||
</div>
|
||||
<div class="panel-box__sub">点选即可修改,每项保存后立即生效;未保存的修改不生效。</div>
|
||||
<div v-for="schema in RULE_SCHEMAS" :key="schema.key" class="rule-section">
|
||||
<div v-for="schema in ruleSchemas" :key="schema.key" class="rule-section">
|
||||
<div class="rule-section__head">
|
||||
<span class="rule-section__title">{{ schema.title }}</span>
|
||||
<span class="rule-section__desc">{{ schema.desc }}</span>
|
||||
@@ -99,6 +105,35 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 课程分类:rule-configs course_category_dict,课程管理筛选/表单下拉选项来源 -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">课程分类</span>
|
||||
<t-button variant="outline" size="small" :disabled="!categoriesDirty" :loading="categoriesSaving" @click="onSaveCategories">保存</t-button>
|
||||
</div>
|
||||
<div class="panel-box__sub">课程管理列表「按分类查询」与「新增课程」弹窗的分类下拉选项;预设之外可在课程表单直接输入自定义分类。</div>
|
||||
<div class="category-editor">
|
||||
<t-tag
|
||||
v-for="c in categoryDraft"
|
||||
:key="c"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
closable
|
||||
@close="onRemoveCategory(c)"
|
||||
>{{ c }}</t-tag>
|
||||
<t-input
|
||||
v-model="categoryInput"
|
||||
class="category-input"
|
||||
size="small"
|
||||
clearable
|
||||
placeholder="输入新分类后回车或点添加"
|
||||
@enter="onAddCategory"
|
||||
/>
|
||||
<t-button variant="outline" size="small" :disabled="!categoryInput.trim()" @click="onAddCategory">添加</t-button>
|
||||
<t-button variant="text" theme="primary" size="small" class="category-reset" @click="onResetCategories">恢复默认</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 高级配置:未提供点选表单的规则键,保留 JSON 编辑兜底 -->
|
||||
<div v-if="advancedRows.length" class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
@@ -115,8 +150,64 @@
|
||||
</template>
|
||||
</t-table>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
|
||||
<!-- 卡片3:推送记录(逐人企微/站内投递明细;手动触发周一讲师提醒) -->
|
||||
<!-- 推送管理:推送提醒参数配置 + 推送投递记录 -->
|
||||
<t-tab-panel value="notify" label="推送管理">
|
||||
<!-- 推送提醒配置(与业务规则同款点选式表单) -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">推送提醒配置</span>
|
||||
</div>
|
||||
<div class="panel-box__sub">点选即可修改,每项保存后立即生效;未保存的修改不生效。</div>
|
||||
<div v-for="schema in notifySchemas" :key="schema.key" class="rule-section">
|
||||
<div class="rule-section__head">
|
||||
<span class="rule-section__title">{{ schema.title }}</span>
|
||||
<span class="rule-section__desc">{{ schema.desc }}</span>
|
||||
<t-button
|
||||
variant="outline"
|
||||
size="small"
|
||||
:disabled="!isDirty(schema.key)"
|
||||
:loading="savingKey === schema.key"
|
||||
@click="onSaveRule(schema.key)"
|
||||
>保存</t-button>
|
||||
</div>
|
||||
<div class="rule-section__fields">
|
||||
<div
|
||||
v-for="field in schema.fields"
|
||||
:key="field.key"
|
||||
class="rule-field"
|
||||
:class="{ 'rule-field--block': field.type === 'text' }"
|
||||
>
|
||||
<span class="rule-field__label">{{ field.label }}</span>
|
||||
<t-input-number
|
||||
v-if="field.type === 'number'"
|
||||
v-model="ruleValues[schema.key][field.key]"
|
||||
:min="field.min"
|
||||
:max="field.max"
|
||||
theme="normal"
|
||||
size="small"
|
||||
class="rule-field__input"
|
||||
/>
|
||||
<t-switch
|
||||
v-else-if="field.type === 'switch'"
|
||||
v-model="ruleValues[schema.key][field.key]"
|
||||
/>
|
||||
<t-textarea
|
||||
v-else
|
||||
v-model="ruleValues[schema.key][field.key]"
|
||||
:autosize="{ minRows: 2, maxRows: 4 }"
|
||||
:placeholder="field.placeholder"
|
||||
class="rule-field__textarea"
|
||||
/>
|
||||
<span v-if="field.unit" class="rule-field__unit">{{ field.unit }}</span>
|
||||
<span v-if="field.vars" class="rule-field__vars">可用变量:{{ field.vars }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 推送记录(逐人企微/站内投递明细;手动触发周一讲师提醒) -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">推送记录</span>
|
||||
@@ -151,12 +242,15 @@
|
||||
展示最近 {{ pushLogs.length }} 条;pending/sending=排队与投递中,sent=企微已送达,skipped=收件人未绑定企微等跳过,dead=重试耗尽,空=仅站内通知。
|
||||
</div>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
|
||||
<!-- 卡片4:导入模板管理(上传自定义 Excel 模板替换内置默认) -->
|
||||
<!-- 导入模板:上传自定义 Excel 模板替换内置默认 -->
|
||||
<t-tab-panel value="templates" label="导入模板">
|
||||
<!-- 导入模板管理(上传自定义 Excel 模板替换内置默认) -->
|
||||
<div class="panel-box">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">导入模板</span>
|
||||
<span class="panel-box__sub">上传后,培训计划批量导入与题库 Excel 导入的下载入口即刻使用新模板</span>
|
||||
<span class="panel-box__sub">上传后,培训计划批量导入、题库 Excel 导入与课程管理批量导入的下载入口即刻使用新模板</span>
|
||||
</div>
|
||||
<t-table :data="templates" :columns="templateColumns" row-key="template_key" size="small" :loading="templateLoading">
|
||||
<template #file_name="{ row }">
|
||||
@@ -189,11 +283,13 @@
|
||||
@change="onUploadFile"
|
||||
/>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
</t-tabs>
|
||||
|
||||
<!-- 角色编辑弹窗 -->
|
||||
<t-dialog
|
||||
v-model:visible="roleDialogVisible"
|
||||
:header="roleForm.mode === 'add' ? '新增职称角色' : `编辑职称角色 · ${roleForm.label || roleForm.key}`"
|
||||
:header="roleForm.mode === 'add' ? '新增角色' : `编辑角色 · ${roleForm.label || roleForm.key}`"
|
||||
width="480"
|
||||
>
|
||||
<t-form label-width="88px">
|
||||
@@ -244,6 +340,8 @@
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
COURSE_CATEGORY_DICT_RULE_KEY,
|
||||
DEFAULT_COURSE_CATEGORIES,
|
||||
ROLE_DICT_RULE_KEY,
|
||||
deleteTrainingTemplate,
|
||||
fetchRoleDict,
|
||||
@@ -265,6 +363,9 @@ import {
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
import { downloadTrainingTemplate } from '../trainingTemplates'
|
||||
|
||||
// [2026-11 需求] 配置中心 tab 切换(角色权限/业务规则/推送管理/导入模板)
|
||||
const activeTab = ref('roles')
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const editVisible = ref(false)
|
||||
@@ -393,6 +494,8 @@ interface RuleSchemaDesc {
|
||||
title: string
|
||||
desc: string
|
||||
fields: RuleFieldDesc[]
|
||||
// group:notify = 推送提醒类配置,配置中心归入「推送管理」tab;缺省归「业务规则」tab。
|
||||
group?: 'notify'
|
||||
// serialize UI 表单值 → tr_rule_configs 落库值(默认原样 JSON);
|
||||
// notify_remind_days(数组)/notify_push_enabled(bool) 等非对象契约用。
|
||||
serialize?: (v: Record<string, any>) => any
|
||||
@@ -439,6 +542,7 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
// (training_scheduler.go loadNotifyConfig);原 remind_policy(t3/t1/third_week/
|
||||
// month_end)从未被后端读取,由本卡替换(third_week/month_end 无实现,随卡移除)。
|
||||
key: 'notify_remind_days',
|
||||
group: 'notify',
|
||||
title: '开课提醒时点',
|
||||
desc: '调度器按提前天数生成讲师授课提醒;学员开课通知由场次"通知方式"决定(立即或前一天),不受本项影响',
|
||||
fields: [
|
||||
@@ -457,6 +561,7 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
},
|
||||
{
|
||||
key: 'notify_push_enabled',
|
||||
group: 'notify',
|
||||
title: '企微推送总开关',
|
||||
desc: '关闭后新产生的通知只保留站内流水,不再推送企业微信;已入队消息不受影响',
|
||||
fields: [{ key: 'enabled', label: '启用企微推送', type: 'switch' }],
|
||||
@@ -466,6 +571,7 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
},
|
||||
{
|
||||
key: 'notify_weekly_lecturer',
|
||||
group: 'notify',
|
||||
title: '周一讲师未完成提醒',
|
||||
desc: '每周一上午向当月仍有未结束场次的讲师推送汇总提醒(标题带第 N 周);讲师场次全部结束即自动停推',
|
||||
fields: [
|
||||
@@ -482,6 +588,7 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
// [2026-11 需求] 提醒推送文案可编辑:各提醒场景的标题/内容模板,保存后新推送即刻生效;
|
||||
// {占位符} 渲染时替换为实际值,清空保存即恢复内置默认文案(后端空值回落默认)。
|
||||
key: 'notify_text_templates',
|
||||
group: 'notify',
|
||||
title: '提醒推送文案',
|
||||
desc: '各提醒推送的标题与内容模板,支持 {占位符} 替换实际值;清空并保存即恢复内置默认文案,对保存后的新推送生效',
|
||||
fields: [
|
||||
@@ -565,6 +672,58 @@ const DEFAULT_RULE_VALUES: Record<string, Record<string, any>> = {
|
||||
|
||||
const RULE_SCHEMA_KEYS = new Set(RULE_SCHEMAS.map((s) => s.key))
|
||||
|
||||
// tab 分组:业务规则(签到/评分/积分/达标线/滚动)与推送提醒(notify_*)各自成 tab
|
||||
const ruleSchemas = RULE_SCHEMAS.filter((s) => s.group !== 'notify')
|
||||
const notifySchemas = RULE_SCHEMAS.filter((s) => s.group === 'notify')
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 课程分类(course_category_dict):课程管理筛选/表单下拉选项字典,
|
||||
// tag 列表增删 + 保存;保存后课程管理页下次拉取即生效。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const categoryDraft = ref<string[]>([])
|
||||
const categorySnapshot = ref('[]')
|
||||
const categoryInput = ref('')
|
||||
const categoriesSaving = ref(false)
|
||||
const categoriesDirty = computed(() => JSON.stringify(categoryDraft.value) !== categorySnapshot.value)
|
||||
|
||||
const onAddCategory = () => {
|
||||
const name = categoryInput.value.trim()
|
||||
if (!name) return
|
||||
if (categoryDraft.value.some((c) => c === name)) {
|
||||
MessagePlugin.warning(`分类「${name}」已存在`)
|
||||
return
|
||||
}
|
||||
categoryDraft.value = [...categoryDraft.value, name]
|
||||
categoryInput.value = ''
|
||||
}
|
||||
|
||||
const onRemoveCategory = (name: string) => {
|
||||
categoryDraft.value = categoryDraft.value.filter((c) => c !== name)
|
||||
}
|
||||
|
||||
// 恢复默认分类(仅改草稿,点「保存」后落库生效)
|
||||
const onResetCategories = () => {
|
||||
categoryDraft.value = [...DEFAULT_COURSE_CATEGORIES]
|
||||
}
|
||||
|
||||
const onSaveCategories = async () => {
|
||||
if (!categoryDraft.value.length) {
|
||||
MessagePlugin.warning('至少保留一个分类')
|
||||
return
|
||||
}
|
||||
categoriesSaving.value = true
|
||||
try {
|
||||
await saveRuleConfig(COURSE_CATEGORY_DICT_RULE_KEY, { categories: categoryDraft.value })
|
||||
categorySnapshot.value = JSON.stringify(categoryDraft.value)
|
||||
MessagePlugin.success('课程分类已保存并生效')
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||
} finally {
|
||||
categoriesSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const ruleValues = ref<Record<string, Record<string, any>>>({})
|
||||
const savedSnapshot = ref<Record<string, string>>({})
|
||||
const savingKey = ref('')
|
||||
@@ -594,8 +753,15 @@ const applyConfigs = (configs: TrainingRuleConfig[]) => {
|
||||
ruleValues.value = values
|
||||
savedSnapshot.value = snapshot
|
||||
advancedRows.value = configs.filter(
|
||||
(c) => !RULE_SCHEMA_KEYS.has(c.rule_key) && c.rule_key !== ROLE_DICT_RULE_KEY,
|
||||
(c) => !RULE_SCHEMA_KEYS.has(c.rule_key) && c.rule_key !== ROLE_DICT_RULE_KEY && c.rule_key !== COURSE_CATEGORY_DICT_RULE_KEY,
|
||||
)
|
||||
// 课程分类字典:有专属卡片,缺省回退默认分类(与 fetchCourseCategories 同口径)
|
||||
const categoryRaw = configs.find((c) => c.rule_key === COURSE_CATEGORY_DICT_RULE_KEY)?.rule_value?.categories
|
||||
const categories = Array.isArray(categoryRaw)
|
||||
? categoryRaw.filter((c): c is string => typeof c === 'string' && !!c.trim())
|
||||
: [...DEFAULT_COURSE_CATEGORIES]
|
||||
categoryDraft.value = categories
|
||||
categorySnapshot.value = JSON.stringify(categories)
|
||||
}
|
||||
|
||||
const loadAll = async () => {
|
||||
@@ -853,6 +1019,29 @@ watch(pushScene, () => loadPushLogs())
|
||||
display: none;
|
||||
}
|
||||
|
||||
// ---- tab 化布局:tab 内容区与 panel-box 间距 ----
|
||||
.rule-tabs {
|
||||
:deep(.t-tab-panel) {
|
||||
padding: 12px 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 课程分类(tag 列表增删编辑) ----
|
||||
.category-editor {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.category-input {
|
||||
width: 220px;
|
||||
}
|
||||
|
||||
.category-reset {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
margin-top: 8px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
* 模板按业务键管理:配置中心上传的自定义版本存后端 tr_templates 并全端生效,
|
||||
* 未上传时由后端回退内置默认(docs/moban 随二进制分发)。
|
||||
* - demand_collection 教育训练需求表模板.xlsx(2026-11 起的系统内置默认,
|
||||
* 含「计划培训时间」列):培训计划「年度需求收集 → 批量导入」使用;
|
||||
* 列:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓/计划培训时间/讲师/备注;
|
||||
* 后端下载时按新布局注入组织架构下拉(部门 B/参加人员 D/讲师 I)。
|
||||
* 含「计划培训月份」列):培训计划「年度需求收集 → 批量导入」使用;
|
||||
* 列:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓/计划培训月份/讲师/备注;
|
||||
* 后端下载时动态注入:标题年份=下一年度、课程名称下拉(课程管理 C)、
|
||||
* 计划培训月份下拉(1~12 H)、部门/讲师下拉(部门 B/讲师 I)。
|
||||
* - question_bank 部门培训课程试题(题库导入版)模板.xlsx:
|
||||
* 「题库与考试 → Excel 批量导入」与「培训课程 → 创建课程 → 关联题库」指引使用;
|
||||
* 工作表:单选题/多选题/判断题,列:题目/课程名称/难度/正确答案/答案A..答案L。
|
||||
* - course_library 课程管理导入模板.xlsx:「课程管理 → 批量导入」使用;
|
||||
* 列:课程名称/说明/分类/类型/线上,线下/讲师/时长(学时)/课件。
|
||||
*/
|
||||
import { downloadTrainingTemplateFile, type TrainingTemplateKey } from '@/api/training'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
@@ -17,16 +20,19 @@ export type { TrainingTemplateKey }
|
||||
|
||||
export const DEMAND_TEMPLATE_KEY: TrainingTemplateKey = 'demand_collection'
|
||||
export const QUESTION_TEMPLATE_KEY: TrainingTemplateKey = 'question_bank'
|
||||
export const COURSE_LIBRARY_TEMPLATE_KEY: TrainingTemplateKey = 'course_library'
|
||||
|
||||
export const TRAINING_TEMPLATE_LABELS: Record<TrainingTemplateKey, string> = {
|
||||
demand_collection: '教育训练需求表模板',
|
||||
question_bank: '部门培训课程试题(题库导入版)模板',
|
||||
course_library: '课程管理导入模板',
|
||||
}
|
||||
|
||||
// 兜底保存扩展名与内置默认文件一致(后端返回的 fileName 缺失时用)。
|
||||
const TRAINING_TEMPLATE_EXT: Record<TrainingTemplateKey, string> = {
|
||||
demand_collection: '.xlsx',
|
||||
question_bank: '.xlsx',
|
||||
course_library: '.xlsx',
|
||||
}
|
||||
|
||||
// 触发浏览器保存 Blob(带登录态经接口下载;fileName 可传列表接口返回的实际文件名)
|
||||
|
||||
@@ -26,7 +26,8 @@ function trainingPreviewMockApi(): Plugin {
|
||||
server.middlewares.use((req, res, next) => {
|
||||
const raw = req.url || ''
|
||||
const path = raw.split('?')[0]
|
||||
if (path.startsWith('/api/v1/training/')) {
|
||||
// 拦截培训域与知识库文档列表(课程管理「从知识库选择课件」演示数据)
|
||||
if (path.startsWith('/api/v1/training/') || path.startsWith('/api/v1/knowledge-bases/')) {
|
||||
// 模板文件下载:直接回真实 Excel 二进制
|
||||
const fileMatch = path.match(/^\/api\/v1\/training\/templates\/(demand_collection|question_bank)\/file$/)
|
||||
if (req.method === 'GET' && fileMatch) {
|
||||
@@ -58,12 +59,14 @@ function trainingPreviewMockApi(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// mergeConfig(base, override):第二参优先——mock 插件与端口覆盖必须放在
|
||||
// baseConfig 之后,否则 server.port 会被 base 的 5173 覆盖,预览落错端口。
|
||||
export default mergeConfig(
|
||||
baseConfig,
|
||||
defineConfig({
|
||||
plugins: [trainingPreviewMockApi()],
|
||||
server: {
|
||||
port: 5175,
|
||||
},
|
||||
}),
|
||||
baseConfig,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 培训业务唯一编号(000153)
|
||||
// 计数器表 tr_code_counters(tenant_id, code_key) 主键UPSERT原子递增,
|
||||
// key 形如 AP:2026 / MP:202611 / CRS / QB;存量数据由迁移回填并播种计数器。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// NextCodeValue 返回 code_key 下一个流水值(原子递增,并发安全)。
|
||||
func (r *trainingRepository) NextCodeValue(ctx context.Context, tenantID uint64, key string) (int64, error) {
|
||||
var value int64
|
||||
err := r.db.WithContext(ctx).Raw(`
|
||||
INSERT INTO tr_code_counters (tenant_id, code_key, value, updated_at)
|
||||
VALUES (?, ?, 1, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (tenant_id, code_key)
|
||||
DO UPDATE SET value = tr_code_counters.value + 1, updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING value`, tenantID, key).Scan(&value).Error
|
||||
return value, err
|
||||
}
|
||||
|
||||
var _ interfaces.TrainingRepository = (*trainingRepository)(nil)
|
||||
@@ -21,9 +21,9 @@ func (r *trainingRepository) CreateQuestionBank(ctx context.Context, bank *types
|
||||
|
||||
// ReplaceQuestionBankByName 同名题库重导入即替换:软删同租户同名旧题库及其全部
|
||||
// 题目与试卷(含缓存的 ONLINE 自学卷,重导后按新解析重建),返回旧题库的
|
||||
// 课程关联供新题库继承;无同名旧库时原样返回空串。
|
||||
func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, error) {
|
||||
oldCourseID := ""
|
||||
// 课程/课程管理关联供新题库继承;无同名旧库时原样返回空串。
|
||||
func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, string, error) {
|
||||
oldCourseID, oldLibraryCourseID := "", ""
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var banks []*types.TrainingQuestionBank
|
||||
if err := tx.Where("tenant_id = ? AND name = ? AND deleted_at IS NULL", tenantID, name).
|
||||
@@ -39,6 +39,9 @@ func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tena
|
||||
if oldCourseID == "" && b.CourseID != "" {
|
||||
oldCourseID = b.CourseID
|
||||
}
|
||||
if oldLibraryCourseID == "" && b.LibraryCourseID != "" {
|
||||
oldLibraryCourseID = b.LibraryCourseID
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
if err := tx.Model(&types.TrainingQuestionBank{}).
|
||||
@@ -55,7 +58,7 @@ func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tena
|
||||
Where("tenant_id = ? AND bank_id IN ?", tenantID, ids).
|
||||
Update("deleted_at", now).Error
|
||||
})
|
||||
return oldCourseID, err
|
||||
return oldCourseID, oldLibraryCourseID, err
|
||||
}
|
||||
|
||||
// ListQuestionBanks returns a page of question banks.
|
||||
@@ -110,6 +113,38 @@ func (r *trainingRepository) GetQuestionBankByCourse(ctx context.Context, tenant
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
// GetQuestionBankByLibraryCourse 取课程管理条目下的题库列表(试题随课程管理维护,
|
||||
// 000153;updated_at 降序,支持一个课程多个题库)。
|
||||
func (r *trainingRepository) GetQuestionBankByLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error) {
|
||||
var banks []*types.TrainingQuestionBank
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND library_course_id = ? AND deleted_at IS NULL", tenantID, libraryCourseID).
|
||||
Order("updated_at DESC").Find(&banks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return banks, nil
|
||||
}
|
||||
|
||||
// DeleteQuestionBank 软删题库及其全部题目与缓存试卷(000153,试题抽屉删除入口)。
|
||||
func (r *trainingRepository) DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
now := time.Now()
|
||||
if err := tx.Model(&types.TrainingQuestionBank{}).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, bankID).
|
||||
Update("deleted_at", now).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&types.TrainingQuestion{}).
|
||||
Where("tenant_id = ? AND bank_id = ?", tenantID, bankID).
|
||||
Update("deleted_at", now).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&types.TrainingPaper{}).
|
||||
Where("tenant_id = ? AND bank_id = ?", tenantID, bankID).
|
||||
Update("deleted_at", now).Error
|
||||
})
|
||||
}
|
||||
|
||||
// GetSelfStudyPaperByBank fetches the bank's course self-study paper
|
||||
// (无场次、version=ONLINE,与线下场次组卷区分)。
|
||||
func (r *trainingRepository) GetSelfStudyPaperByBank(ctx context.Context, tenantID uint64, bankID string) (*types.TrainingPaper, error) {
|
||||
@@ -130,6 +165,22 @@ func (r *trainingRepository) UpdateQuestionBankCourse(ctx context.Context, tenan
|
||||
Update("course_id", courseID).Error
|
||||
}
|
||||
|
||||
// RelinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):先解除该条目
|
||||
// 下既有题库的挂接,再把所选题库指向该条目(更换即整体替换,其他课程的题库不受影响)。
|
||||
func (r *trainingRepository) RelinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&types.TrainingQuestionBank{}).
|
||||
Where("tenant_id = ? AND library_course_id = ? AND id <> ? AND deleted_at IS NULL",
|
||||
tenantID, libraryCourseID, bankID).
|
||||
Update("library_course_id", "").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&types.TrainingQuestionBank{}).
|
||||
Where("tenant_id = ? AND id = ? AND deleted_at IS NULL", tenantID, bankID).
|
||||
Update("library_course_id", libraryCourseID).Error
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateQuestionBankCount refreshes the denormalized question count.
|
||||
func (r *trainingRepository) UpdateQuestionBankCount(ctx context.Context, tenantID uint64, bankID string, count int) error {
|
||||
return r.db.WithContext(ctx).Model(&types.TrainingQuestionBank{}).
|
||||
@@ -145,6 +196,54 @@ func (r *trainingRepository) BatchCreateQuestions(ctx context.Context, questions
|
||||
return r.db.WithContext(ctx).Create(&questions).Error
|
||||
}
|
||||
|
||||
// CreateQuestion 插入单题(000153,试题抽屉手工新增)。
|
||||
func (r *trainingRepository) CreateQuestion(ctx context.Context, question *types.TrainingQuestion) error {
|
||||
return r.db.WithContext(ctx).Create(question).Error
|
||||
}
|
||||
|
||||
// GetQuestion 取单题。
|
||||
func (r *trainingRepository) GetQuestion(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestion, error) {
|
||||
var q types.TrainingQuestion
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).First(&q).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &q, nil
|
||||
}
|
||||
|
||||
// UpdateQuestion 更新单题(题干/选项/答案/分值等全字段)。
|
||||
func (r *trainingRepository) UpdateQuestion(ctx context.Context, question *types.TrainingQuestion) error {
|
||||
return r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
|
||||
Where("tenant_id = ? AND id = ?", question.TenantID, question.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"seq_no": question.SeqNo,
|
||||
"type": question.Type,
|
||||
"stem": question.Stem,
|
||||
"options": question.Options,
|
||||
"answer": question.Answer,
|
||||
"score": question.Score,
|
||||
"difficulty": question.Difficulty,
|
||||
"knowledge_point": question.KnowledgePoint,
|
||||
"analysis": question.Analysis,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteQuestion 软删单题(000153,试题抽屉删除入口)。
|
||||
func (r *trainingRepository) DeleteQuestion(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Update("deleted_at", time.Now()).Error
|
||||
}
|
||||
|
||||
// CountBankQuestions 统计题库现存未删题目数(增删题目后刷新冗余计数)。
|
||||
func (r *trainingRepository) CountBankQuestions(ctx context.Context, tenantID uint64, bankID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
|
||||
Where("tenant_id = ? AND bank_id = ? AND deleted_at IS NULL", tenantID, bankID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ListQuestions returns all questions of a bank ordered by seq_no.
|
||||
func (r *trainingRepository) ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error) {
|
||||
var items []*types.TrainingQuestion
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 课程管理(课程资产主数据,tr_course_library,000151)。
|
||||
// 月培训计划的「计划名称」从本表选择,选中后经 tr_courses.library_course_id 关联。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ListCourseLibrary returns a page of course-library items with keyword filter
|
||||
// (分类/类型等前端本地过滤,数据量小全量加载)。
|
||||
func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
|
||||
// 列名统一以 tr_course_library 限定:JOIN users 后 tenant_id/updated_at 等
|
||||
// 同名列不加限定会报 SQLSTATE 42702 歧义(与 ListCourses 同口径)。
|
||||
tx := r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).Where("tr_course_library.tenant_id = ?", tenantID)
|
||||
if q != nil {
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("tr_course_library.name ILIKE ?", "%"+q.Keyword+"%")
|
||||
}
|
||||
}
|
||||
var total int64
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
page, pageSize := 1, 100
|
||||
if q != nil {
|
||||
if q.Page > 0 {
|
||||
page = q.Page
|
||||
}
|
||||
if q.PageSize > 0 {
|
||||
pageSize = q.PageSize
|
||||
}
|
||||
}
|
||||
var items []*types.TrainingCourseLibrary
|
||||
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Order("tr_course_library.updated_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&items).Error
|
||||
return items, total, err
|
||||
}
|
||||
|
||||
// GetCourseLibraryItem fetches one course-library item.
|
||||
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||
var item types.TrainingCourseLibrary
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Where("tr_course_library.tenant_id = ? AND tr_course_library.id = ?", tenantID, id).First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// CreateCourseLibraryItem inserts one course-library item.
|
||||
func (r *trainingRepository) CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error {
|
||||
return r.db.WithContext(ctx).Create(item).Error
|
||||
}
|
||||
|
||||
// UpdateCourseLibraryItem updates mutable course-library fields (file columns included:
|
||||
// 课件文件上传后随行更新,清空即置空)。
|
||||
func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error {
|
||||
return r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).
|
||||
Where("tenant_id = ? AND id = ?", item.TenantID, item.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"name": item.Name,
|
||||
"owner_dept_id": item.OwnerDeptID,
|
||||
"description": item.Description,
|
||||
"suitable_members": item.SuitableMembers,
|
||||
"category": item.Category,
|
||||
"type": item.Type,
|
||||
"mode": item.Mode,
|
||||
"lecturer_id": item.LecturerID,
|
||||
"lecturer_external": item.LecturerExternal,
|
||||
"hours": item.Hours,
|
||||
"material_name": item.MaterialName,
|
||||
"file_key": item.FileKey,
|
||||
"file_name": item.FileName,
|
||||
"file_size": item.FileSize,
|
||||
// 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。
|
||||
"knowledge_id": item.KnowledgeID,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// UpdateCourseLibraryPublishStatus 更新课程管理条目发布状态(000154):
|
||||
// published 已发布 / offline 已下线,供培训中心「和信课程」目录过滤。
|
||||
func (r *trainingRepository) UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
|
||||
return r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Updates(map[string]interface{}{
|
||||
"publish_status": status,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
// BatchCreateCourseLibrary inserts course-library items in one batch (Excel 导入)。
|
||||
func (r *trainingRepository) BatchCreateCourseLibrary(ctx context.Context, items []*types.TrainingCourseLibrary) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(&items).Error
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem soft-deletes one course-library item.
|
||||
func (r *trainingRepository) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.TrainingCourseLibrary{}).Error
|
||||
}
|
||||
@@ -69,6 +69,22 @@ func (r *trainingRepository) ListDemands(ctx context.Context, tenantID uint64, q
|
||||
return items, total, err
|
||||
}
|
||||
|
||||
// ListDemandYears returns distinct demand years of the tenant, latest first
|
||||
// (年度需求收集页年份下拉数据源:列表中所有计划培训实际年份;
|
||||
// deptID 非空时收窄到该部门,与纯课长数据范围口径一致)。
|
||||
func (r *trainingRepository) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) {
|
||||
var years []int
|
||||
tx := r.db.WithContext(ctx).Model(&types.TrainingDemand{}).
|
||||
Where("tenant_id = ? AND year > 0", tenantID)
|
||||
if deptID != "" {
|
||||
tx = tx.Where("dept_id = ?", deptID)
|
||||
}
|
||||
err := tx.Distinct().
|
||||
Order("year DESC").
|
||||
Pluck("year", &years).Error
|
||||
return years, err
|
||||
}
|
||||
|
||||
// GetDemand fetches one demand.
|
||||
func (r *trainingRepository) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) {
|
||||
var d types.TrainingDemand
|
||||
@@ -375,6 +391,8 @@ func (r *trainingRepository) UpdateCourse(ctx context.Context, course *types.Tra
|
||||
"session_count": course.SessionCount,
|
||||
"lecturer_external": course.LecturerExternal,
|
||||
"remark": course.Remark,
|
||||
// 课程管理关联(月培训计划「计划名称」来源,000151)。
|
||||
"library_course_id": course.LibraryCourseID,
|
||||
}).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,62 @@ func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces
|
||||
|
||||
func trainingNewID() string { return uuid.New().String() }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 唯一编号(000153,前缀+年月+流水,租户内递增)
|
||||
// 编号计数器失败时 fail-open(记录日志,编号留空),不阻断主流程。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// nextTrainingCode 经计数器取下一流水并按 format 拼业务编号。
|
||||
func (s *trainingService) nextTrainingCode(ctx context.Context, tenantID uint64, key string, format func(int64) string) string {
|
||||
value, err := s.repo.NextCodeValue(ctx, tenantID, key)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to allocate training code", err, "key", key)
|
||||
return ""
|
||||
}
|
||||
return format(value)
|
||||
}
|
||||
|
||||
// nextDemandCode 年计划编号:AP-<year>-####(按年分段)。
|
||||
func (s *trainingService) nextDemandCode(ctx context.Context, tenantID uint64, year int) string {
|
||||
return s.nextTrainingCode(ctx, tenantID, fmt.Sprintf("AP:%d", year), func(v int64) string {
|
||||
return fmt.Sprintf("AP-%d-%04d", year, v)
|
||||
})
|
||||
}
|
||||
|
||||
// nextMonthPlanCode 月度计划编号:MP-<YYYYMM>-####(按授课月份分段)。
|
||||
func (s *trainingService) nextMonthPlanCode(ctx context.Context, tenantID uint64, year, month int) string {
|
||||
key := fmt.Sprintf("MP:%04d%02d", year, month)
|
||||
return s.nextTrainingCode(ctx, tenantID, key, func(v int64) string {
|
||||
return fmt.Sprintf("MP-%04d%02d-%04d", year, month, v)
|
||||
})
|
||||
}
|
||||
|
||||
// nextCourseLibraryCode 课程编号:CRS-####(租户内流水)。
|
||||
func (s *trainingService) nextCourseLibraryCode(ctx context.Context, tenantID uint64) string {
|
||||
return s.nextTrainingCode(ctx, tenantID, "CRS", func(v int64) string {
|
||||
return fmt.Sprintf("CRS-%04d", v)
|
||||
})
|
||||
}
|
||||
|
||||
// nextQuestionBankCode 试题库编号:QB-####(租户内流水)。
|
||||
func (s *trainingService) nextQuestionBankCode(ctx context.Context, tenantID uint64) string {
|
||||
return s.nextTrainingCode(ctx, tenantID, "QB", func(v int64) string {
|
||||
return fmt.Sprintf("QB-%04d", v)
|
||||
})
|
||||
}
|
||||
|
||||
// monthPlanYearMonth 从课程授课时间(teach_time,YYYY-MM 或 YYYY-MM-DD HH:mm)
|
||||
// 提取计划编号分段年月;解析失败回退当前年月。
|
||||
func monthPlanYearMonth(teachTime string, now time.Time) (int, int) {
|
||||
if len(teachTime) >= 7 {
|
||||
var year, month int
|
||||
if _, err := fmt.Sscanf(teachTime[:7], "%d-%d", &year, &month); err == nil && year > 0 && month >= 1 && month <= 12 {
|
||||
return year, month
|
||||
}
|
||||
}
|
||||
return now.Year(), int(now.Month())
|
||||
}
|
||||
|
||||
func trainingJSONFromSlice(items []string) types.JSON {
|
||||
if len(items) == 0 {
|
||||
return types.JSON([]byte("[]"))
|
||||
@@ -260,6 +316,11 @@ func (s *trainingService) ListDemands(ctx context.Context, tenantID uint64, q *i
|
||||
return s.repo.ListDemands(ctx, tenantID, q)
|
||||
}
|
||||
|
||||
// ListDemandYears returns distinct demand years (desc) for the year filter.
|
||||
func (s *trainingService) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) {
|
||||
return s.repo.ListDemandYears(ctx, tenantID, deptID)
|
||||
}
|
||||
|
||||
// GetDemand fetches one demand.
|
||||
func (s *trainingService) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) {
|
||||
return s.repo.GetDemand(ctx, tenantID, id)
|
||||
@@ -335,6 +396,7 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
}
|
||||
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
|
||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||
// 核验状态默认「待核验」:填报/编辑不自动通过,统一由经理核验确认。
|
||||
msgs := []string{}
|
||||
if demand.DeptID == "" {
|
||||
msgs = append(msgs, "未指定部门")
|
||||
@@ -346,11 +408,7 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
}
|
||||
demand.CheckMsg += m
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
demand.CheckStatus = types.TrainingCheckPassed
|
||||
} else {
|
||||
demand.CheckStatus = types.TrainingCheckPending
|
||||
}
|
||||
demand.CheckStatus = types.TrainingCheckPending
|
||||
if demand.Status == "" {
|
||||
demand.Status = types.TrainingDemandSubmitted
|
||||
}
|
||||
@@ -358,6 +416,8 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
if demand.ID == "" {
|
||||
demand.ID = trainingNewID()
|
||||
demand.TenantID = tenantID
|
||||
// 年计划编号(AP-<year>-####,创建时生成;计数器失败留空不阻断)。
|
||||
demand.Code = s.nextDemandCode(ctx, tenantID, demand.Year)
|
||||
if err := s.repo.CreateDemand(ctx, demand); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -382,21 +442,20 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
|
||||
if demands[i].Year <= 0 {
|
||||
demands[i].Year = time.Now().Year()
|
||||
}
|
||||
// 年计划编号(批量导入逐行生成,同年前缀分段递增)。
|
||||
demands[i].Code = s.nextDemandCode(ctx, tenantID, demands[i].Year)
|
||||
if demands[i].Status == "" {
|
||||
demands[i].Status = types.TrainingDemandSubmitted
|
||||
}
|
||||
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
|
||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
|
||||
msgs := []string{}
|
||||
if demands[i].DeptID == "" {
|
||||
msgs = append(msgs, "未指定部门")
|
||||
}
|
||||
demands[i].CheckMsg = strings.Join(msgs, ";")
|
||||
if len(msgs) == 0 {
|
||||
demands[i].CheckStatus = types.TrainingCheckPassed
|
||||
} else {
|
||||
demands[i].CheckStatus = types.TrainingCheckPending
|
||||
}
|
||||
demands[i].CheckStatus = types.TrainingCheckPending
|
||||
}
|
||||
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -97,18 +97,114 @@ func courseExamStatus(expected int, st *types.TrainingCourseStudyStats) string {
|
||||
}
|
||||
|
||||
// GetCourse returns one course.
|
||||
// courseExamBank 课程考试题库解析(000153):优先取课程直连题库(course_id),
|
||||
// 未绑定时回退课程管理条目下的题库(library_course_id,试题随课程管理维护)。
|
||||
func (s *trainingService) courseExamBank(ctx context.Context, tenantID uint64, course *types.TrainingCourse) (*types.TrainingQuestionBank, error) {
|
||||
if course == nil {
|
||||
return nil, errors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, course.ID); err == nil && bank != nil {
|
||||
return bank, nil
|
||||
}
|
||||
if course.LibraryCourseID == "" {
|
||||
return nil, errors.NewNotFoundError("题库不存在")
|
||||
}
|
||||
banks, err := s.repo.GetQuestionBankByLibraryCourse(ctx, tenantID, course.LibraryCourseID)
|
||||
if err != nil || len(banks) == 0 {
|
||||
return nil, errors.NewNotFoundError("题库不存在")
|
||||
}
|
||||
return banks[0], nil
|
||||
}
|
||||
|
||||
func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourse, error) {
|
||||
course, err := s.repo.GetCourse(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
// 绑定题库即具备在线考试条件(详情页随堂考试入口与 exam_enabled 开关并联)。
|
||||
if bank, bankErr := s.repo.GetQuestionBankByCourse(ctx, tenantID, id); bankErr == nil && bank != nil {
|
||||
// 绑定题库即具备在线考试条件(详情页随堂考试入口与 exam_enabled 开关并联);
|
||||
// 课程自身未绑定时回退课程管理条目的题库(000153)。
|
||||
if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil {
|
||||
course.ExamReady = true
|
||||
}
|
||||
return course, nil
|
||||
}
|
||||
|
||||
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
|
||||
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/
|
||||
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。
|
||||
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
|
||||
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
|
||||
if course.LibraryCourseID == "" {
|
||||
return nil
|
||||
}
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
|
||||
if err != nil || item == nil {
|
||||
logger.Error(ctx, "Failed to load library course for plan binding", err, "library_course_id", course.LibraryCourseID)
|
||||
return nil
|
||||
}
|
||||
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖。
|
||||
course.Name = item.Name
|
||||
course.Type = item.Type
|
||||
course.Mode = item.Mode
|
||||
if item.LecturerID != "" || item.LecturerExternal != "" {
|
||||
course.LecturerID = item.LecturerID
|
||||
course.LecturerExternal = item.LecturerExternal
|
||||
}
|
||||
if !isCreate {
|
||||
return item
|
||||
}
|
||||
// 预填字段:仅新建时带出,后续学时/学分按月度计划维护口径可调。
|
||||
if course.Hours <= 0 {
|
||||
course.Hours = item.Hours
|
||||
}
|
||||
if course.Code == "" {
|
||||
course.Code = item.Code
|
||||
}
|
||||
if len(course.DeptIDs) == 0 || string(course.DeptIDs) == "[]" || string(course.DeptIDs) == "null" {
|
||||
if item.OwnerDeptID != "" {
|
||||
deptIDs, _ := json.Marshal([]string{item.OwnerDeptID})
|
||||
course.DeptIDs = types.JSON(deptIDs)
|
||||
}
|
||||
}
|
||||
if course.PostScope == "" {
|
||||
course.PostScope = item.SuitableMembers
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
|
||||
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
|
||||
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
|
||||
func (s *trainingService) attachLibraryCourseMaterial(ctx context.Context, tenantID uint64, courseID string, item *types.TrainingCourseLibrary, updaterID string) {
|
||||
if item == nil {
|
||||
return
|
||||
}
|
||||
name := item.FileName
|
||||
if name == "" {
|
||||
name = item.MaterialName
|
||||
}
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
kind := "doc"
|
||||
if isVideoMaterialFile("", name) {
|
||||
kind = "video"
|
||||
}
|
||||
material := &types.TrainingMaterial{
|
||||
CourseID: courseID,
|
||||
Kind: kind,
|
||||
Name: name,
|
||||
}
|
||||
if item.KnowledgeID != "" {
|
||||
material.KnowledgeID = item.KnowledgeID
|
||||
} else {
|
||||
material.FileKey = item.FileKey
|
||||
}
|
||||
if _, err := s.CreateMaterial(ctx, tenantID, material, updaterID); err != nil {
|
||||
logger.Error(ctx, "Failed to attach library course material to plan", err, "course_id", courseID)
|
||||
}
|
||||
}
|
||||
|
||||
// SaveCourse creates or updates one course.
|
||||
func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, course *types.TrainingCourse, updaterID string) (*types.TrainingCourse, error) {
|
||||
if course.Name == "" {
|
||||
@@ -124,12 +220,20 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
|
||||
course.ID = trainingNewID()
|
||||
course.TenantID = tenantID
|
||||
course.CreatorID = updaterID
|
||||
// 课程管理信息带出与锁定(000153),课件资料随计划挂接(线上发布/学习页依赖)。
|
||||
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, true)
|
||||
s.attachLibraryCourseMaterial(ctx, tenantID, course.ID, libItem, updaterID)
|
||||
// 月度计划编号(MP-<YYYYMM>-####,按授课月份分段;解析失败取当前月)。
|
||||
year, month := monthPlanYearMonth(course.TeachTime, time.Now())
|
||||
course.PlanCode = s.nextMonthPlanCode(ctx, tenantID, year, month)
|
||||
if err := s.repo.CreateCourse(ctx, course); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return course, nil
|
||||
}
|
||||
course.TenantID = tenantID
|
||||
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。
|
||||
s.applyLibraryCourseBinding(ctx, tenantID, course, false)
|
||||
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
|
||||
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
|
||||
if err != nil {
|
||||
|
||||
@@ -42,6 +42,8 @@ func (s *trainingService) ImportQuestionBank(ctx context.Context, tenantID uint6
|
||||
bank.TenantID = tenantID
|
||||
bank.CreatorID = updaterID
|
||||
bank.QuestionCount = len(questions)
|
||||
// 试题库编号(QB-####,导入/AI 生成统一在此生成,000153)。
|
||||
bank.Code = s.nextQuestionBankCode(ctx, tenantID)
|
||||
if err := s.repo.CreateQuestionBank(ctx, bank); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -70,7 +72,7 @@ func (s *trainingService) ImportQuestionBank(ctx context.Context, tenantID uint6
|
||||
// 模板中的「课程名称」列仅作对照展示,题库与课程的关联以导入弹窗选择的课程为准。
|
||||
// 两种格式均合并解析全部工作表;入库后把原始 Excel 自动同步进系统默认
|
||||
// 「企业培训(题库)」知识库(fail-open),使题库内容支持 AI 对话问答。
|
||||
func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID, libraryCourseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
if fh == nil {
|
||||
return nil, errors.NewBadRequestError("缺少上传文件")
|
||||
}
|
||||
@@ -88,15 +90,18 @@ func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID
|
||||
return nil, err
|
||||
}
|
||||
// 同名重导入即替换:清掉旧题库的题目与缓存试卷(坏数据/旧 ONLINE 卷一并失效),
|
||||
// 调用方未指定归属课程时继承旧题库的课程关联。
|
||||
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
// 调用方未指定归属课程/课程管理条目时继承旧题库的关联。
|
||||
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if courseID == "" {
|
||||
courseID = oldCourseID
|
||||
}
|
||||
bank := &types.TrainingQuestionBank{Name: name, DeptID: deptID, CourseID: courseID}
|
||||
if libraryCourseID == "" {
|
||||
libraryCourseID = oldLibraryCourseID
|
||||
}
|
||||
bank := &types.TrainingQuestionBank{Name: name, DeptID: deptID, CourseID: courseID, LibraryCourseID: libraryCourseID}
|
||||
// 原始 Excel 同步进「企业培训(题库)」知识库(失败不阻断导入),回填 knowledge_id。
|
||||
bank.KnowledgeID = s.syncExcelToQuestionBankKB(ctx, fh, name)
|
||||
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
|
||||
@@ -135,7 +140,7 @@ func (s *trainingService) parseQuestionBankExcel(ctx context.Context, tenantID u
|
||||
// ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档直接导入题库:
|
||||
// 取回 Excel 原件解析建库,文档已在知识库故直接挂接 knowledge_id 不重复上传;
|
||||
// 未指定归属课程时继承同名旧题库的课程关联。
|
||||
func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, libraryCourseID, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
if strings.TrimSpace(knowledgeID) == "" {
|
||||
return nil, errors.NewBadRequestError("缺少知识库文档")
|
||||
}
|
||||
@@ -156,17 +161,113 @@ func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, t
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if courseID == "" {
|
||||
courseID = oldCourseID
|
||||
}
|
||||
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, KnowledgeID: knowledgeID}
|
||||
if libraryCourseID == "" {
|
||||
libraryCourseID = oldLibraryCourseID
|
||||
}
|
||||
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID}
|
||||
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
|
||||
}
|
||||
|
||||
// ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。
|
||||
func (s *trainingService) ListLibraryCourseQuestionBanks(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error) {
|
||||
if libraryCourseID == "" {
|
||||
return nil, errors.NewBadRequestError("缺少课程管理条目")
|
||||
}
|
||||
return s.repo.GetQuestionBankByLibraryCourse(ctx, tenantID, libraryCourseID)
|
||||
}
|
||||
|
||||
// LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体
|
||||
// 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。
|
||||
func (s *trainingService) LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error {
|
||||
if libraryCourseID == "" {
|
||||
return errors.NewBadRequestError("缺少课程管理条目")
|
||||
}
|
||||
if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil {
|
||||
return errors.NewNotFoundError("题库不存在")
|
||||
}
|
||||
return s.repo.RelinkQuestionBankToLibraryCourse(ctx, tenantID, libraryCourseID, bankID)
|
||||
}
|
||||
|
||||
// DeleteQuestionBank 删除题库(连带题目与缓存试卷;试题维护抽屉删除入口,000153)。
|
||||
func (s *trainingService) DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error {
|
||||
if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil {
|
||||
return errors.NewNotFoundError("题库不存在")
|
||||
}
|
||||
return s.repo.DeleteQuestionBank(ctx, tenantID, bankID)
|
||||
}
|
||||
|
||||
// SaveQuestion 单题新增/编辑(id 空 = 新增;题库 question_count 同步刷新,000153)。
|
||||
func (s *trainingService) SaveQuestion(ctx context.Context, tenantID uint64, q *types.TrainingQuestion) (*types.TrainingQuestion, error) {
|
||||
q.Stem = strings.TrimSpace(q.Stem)
|
||||
if q.Stem == "" {
|
||||
return nil, errors.NewBadRequestError("题干不能为空")
|
||||
}
|
||||
if q.Type != types.TrainingQuestionMultiple && q.Type != types.TrainingQuestionJudge {
|
||||
q.Type = types.TrainingQuestionSingle
|
||||
}
|
||||
if q.Difficulty <= 0 {
|
||||
q.Difficulty = 3
|
||||
}
|
||||
if _, err := s.repo.GetQuestionBank(ctx, tenantID, q.BankID); err != nil {
|
||||
return nil, errors.NewNotFoundError("题库不存在")
|
||||
}
|
||||
if q.ID == "" {
|
||||
// 新增:题序排在库内已有题目之后。
|
||||
existing, err := s.repo.ListQuestions(ctx, tenantID, q.BankID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q.ID = trainingNewID()
|
||||
q.TenantID = tenantID
|
||||
q.SeqNo = len(existing) + 1
|
||||
if err := s.repo.CreateQuestion(ctx, q); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
old, err := s.repo.GetQuestion(ctx, tenantID, q.ID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("题目不存在")
|
||||
}
|
||||
q.TenantID = tenantID
|
||||
q.BankID = old.BankID
|
||||
q.SeqNo = old.SeqNo
|
||||
if err := s.repo.UpdateQuestion(ctx, q); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
s.refreshBankQuestionCount(ctx, tenantID, q.BankID)
|
||||
return q, nil
|
||||
}
|
||||
|
||||
// DeleteQuestion 删除单题(题库 question_count 同步刷新,000153)。
|
||||
func (s *trainingService) DeleteQuestion(ctx context.Context, tenantID uint64, questionID string) error {
|
||||
q, err := s.repo.GetQuestion(ctx, tenantID, questionID)
|
||||
if err != nil {
|
||||
return errors.NewNotFoundError("题目不存在")
|
||||
}
|
||||
if err := s.repo.DeleteQuestion(ctx, tenantID, questionID); err != nil {
|
||||
return err
|
||||
}
|
||||
s.refreshBankQuestionCount(ctx, tenantID, q.BankID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshBankQuestionCount 按现存题目数刷新题库冗余计数(fail-open)。
|
||||
func (s *trainingService) refreshBankQuestionCount(ctx context.Context, tenantID uint64, bankID string) {
|
||||
count, err := s.repo.CountBankQuestions(ctx, tenantID, bankID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = s.repo.UpdateQuestionBankCount(ctx, tenantID, bankID, int(count))
|
||||
}
|
||||
|
||||
// questionTemplateCol holds resolved column indexes of the 题库导入版 template header.
|
||||
type questionTemplateCol struct {
|
||||
stem int
|
||||
@@ -855,9 +956,13 @@ const courseSelfStudyPaperVersion = "ONLINE"
|
||||
// GetCourseExamPaper 线上自学考试入口:确保课程线上卷存在并返回学员视角
|
||||
// 题目(卷不存在时按题库全量题数现场组卷,幂等)。
|
||||
func (s *trainingService) GetCourseExamPaper(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingPaper, []*types.TrainingQuestion, error) {
|
||||
// 绑定题库即默认可答题:只要课程关联了题库就允许取卷答题,
|
||||
// exam_enabled 仅决定详情页是否主动展示考试入口。
|
||||
bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, courseID)
|
||||
// 绑定题库即默认可答题:只要课程(或其课程管理条目,000153)关联了题库就允许
|
||||
// 取卷答题,exam_enabled 仅决定详情页是否主动展示考试入口。
|
||||
course, cErr := s.repo.GetCourse(ctx, tenantID, courseID)
|
||||
if cErr != nil || course == nil {
|
||||
return nil, nil, errors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
bank, err := s.courseExamBank(ctx, tenantID, course)
|
||||
if err != nil || bank == nil {
|
||||
return nil, nil, errors.NewNotFoundError("该课程未绑定题库,请联系培训管理员在课程管理中关联题库")
|
||||
}
|
||||
@@ -878,7 +983,11 @@ func (s *trainingService) GetCourseExamPaper(ctx context.Context, tenantID uint6
|
||||
// GetMyCourseExamRecord returns the caller's latest record on the course
|
||||
// self-study paper (nil, false) when未考/未绑题库。
|
||||
func (s *trainingService) GetMyCourseExamRecord(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingExamRecord, bool, error) {
|
||||
bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, courseID)
|
||||
course, cErr := s.repo.GetCourse(ctx, tenantID, courseID)
|
||||
if cErr != nil || course == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
bank, err := s.courseExamBank(ctx, tenantID, course)
|
||||
if err != nil || bank == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
excelize "github.com/xuri/excelize/v2"
|
||||
|
||||
werrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 课程管理(课程资产主数据,tr_course_library,000151)。
|
||||
// 字段口径:课程名称/所属部门(org_depts)/说明/适合人员/分类(配置中心
|
||||
// course_category_dict 可配,支持自定义)/类型(必修课/选修课)/线上或线下/
|
||||
// 讲师/时长/课件(名称登记+可选原始文件)。
|
||||
// 月培训计划的「计划名称」从本表选择,计划创建经 library_course_id 关联。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// courseLibraryTypeLabel 类型展示文案(导出用)。
|
||||
func courseLibraryTypeLabel(t string) string {
|
||||
if t == "elective" {
|
||||
return "选修课"
|
||||
}
|
||||
return "必修课"
|
||||
}
|
||||
|
||||
// courseLibraryModeLabel 形式展示文案(导出用)。
|
||||
func courseLibraryModeLabel(m string) string {
|
||||
if m == types.TrainingCourseModeOnline {
|
||||
return "线上"
|
||||
}
|
||||
return "线下"
|
||||
}
|
||||
|
||||
// normalizeCourseLibrary 归一保存/导入共用的字段口径(名称必填、类型/形式白名单)。
|
||||
func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
|
||||
item.Name = strings.TrimSpace(item.Name)
|
||||
if item.Name == "" {
|
||||
return werrors.NewBadRequestError("课程名称不能为空")
|
||||
}
|
||||
item.OwnerDeptID = strings.TrimSpace(item.OwnerDeptID)
|
||||
item.Category = strings.TrimSpace(item.Category)
|
||||
item.Description = strings.TrimSpace(item.Description)
|
||||
item.SuitableMembers = strings.TrimSpace(item.SuitableMembers)
|
||||
item.LecturerID = strings.TrimSpace(item.LecturerID)
|
||||
item.LecturerExternal = strings.TrimSpace(item.LecturerExternal)
|
||||
item.MaterialName = strings.TrimSpace(item.MaterialName)
|
||||
if item.Type != "elective" {
|
||||
item.Type = "required"
|
||||
}
|
||||
if item.Mode != types.TrainingCourseModeOnline {
|
||||
item.Mode = types.TrainingCourseModeOffline
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListCourseLibraryItems 课程管理列表(月培训计划「计划名称」下拉同源)。
|
||||
func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
|
||||
return s.repo.ListCourseLibrary(ctx, tenantID, q)
|
||||
}
|
||||
|
||||
// SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。
|
||||
func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if item.ID == "" {
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
// 编辑:先取旧值校验存在性,再全量更新(文件字段随行透传,未动即保持原值)。
|
||||
old, err := s.repo.GetCourseLibraryItem(ctx, tenantID, item.ID)
|
||||
if err != nil || old == nil {
|
||||
return nil, werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
// 课件文件:移除标记强制清空;未重新上传时保留原文件信息
|
||||
// (表单不回传 file_key,零值会被误清)。
|
||||
if item.ClearFile {
|
||||
item.FileKey, item.FileName, item.FileSize = "", "", 0
|
||||
item.KnowledgeID = ""
|
||||
} else if item.FileKey == "" && item.FileName == "" && item.FileSize == 0 {
|
||||
item.FileKey, item.FileName, item.FileSize = old.FileKey, old.FileName, old.FileSize
|
||||
}
|
||||
// 知识库文档 id 不随表单回传:未重新上传时保留原值(与新文件一并覆盖)。
|
||||
if item.KnowledgeID == "" {
|
||||
item.KnowledgeID = old.KnowledgeID
|
||||
}
|
||||
item.TenantID = tenantID
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem 软删课程管理条目(月培训计划已创建的历史计划不受影响)。
|
||||
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error {
|
||||
if _, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id); err != nil {
|
||||
return werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
return s.repo.DeleteCourseLibraryItem(ctx, tenantID, id)
|
||||
}
|
||||
|
||||
// GetCourseLibraryItem 取单条课程管理条目(发布/下线等操作后回显)。
|
||||
func (s *trainingService) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return nil, werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 /
|
||||
// offline 已下线;培训中心「和信课程」目录仅展示已发布课程。
|
||||
func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
|
||||
if status != "published" && status != "offline" {
|
||||
return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)")
|
||||
}
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
|
||||
}
|
||||
|
||||
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
|
||||
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
||||
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
||||
if len(items) == 0 {
|
||||
return 0, werrors.NewBadRequestError("没有可导入的课程数据")
|
||||
}
|
||||
rows := make([]*types.TrainingCourseLibrary, 0, len(items))
|
||||
for _, item := range items {
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
continue // 缺课程名称的行跳过(前端同步提示跳过行数)
|
||||
}
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 课程编号逐行生成(CRS-####)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
rows = append(rows, item)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return 0, werrors.NewBadRequestError("没有可导入的课程数据(未填课程名称的行已跳过)")
|
||||
}
|
||||
if err := s.repo.BatchCreateCourseLibrary(ctx, rows); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
logger.Infof(ctx, "[Training] course library imported, tenant=%d rows=%d importer=%s", tenantID, len(rows), updaterID)
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// ExportCourseLibrary 导出课程管理 Excel(ids 空 = 全量;当前筛选由前端传 ids)。
|
||||
func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (string, []byte, error) {
|
||||
items, _, err := s.repo.ListCourseLibrary(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 5000})
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
keep := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
keep[id] = true
|
||||
}
|
||||
filtered := items[:0]
|
||||
for _, item := range items {
|
||||
if keep[item.ID] {
|
||||
filtered = append(filtered, item)
|
||||
}
|
||||
}
|
||||
items = filtered
|
||||
}
|
||||
f := excelize.NewFile()
|
||||
sheet := "课程管理"
|
||||
f.SetSheetName("Sheet1", sheet)
|
||||
// 列口径对齐《教育训练需求表》:所属部门=主办单位,适合人员=参加人员,
|
||||
// 课件=课件收集;导入解析端(LibraryPanel onImportExcel)两套列名均兼容。
|
||||
headers := []string{"课程编号", "所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
|
||||
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建时间"}
|
||||
for i, h := range headers {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
_ = f.SetCellValue(sheet, cell, h)
|
||||
}
|
||||
hoursText := func(h float64) string {
|
||||
if h == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%g", h)
|
||||
}
|
||||
for r, item := range items {
|
||||
lecturer := item.LecturerName
|
||||
if lecturer == "" {
|
||||
lecturer = item.LecturerExternal
|
||||
}
|
||||
values := []string{item.Code, item.OwnerDeptName, item.Name, item.Description, item.SuitableMembers, item.Category,
|
||||
courseLibraryTypeLabel(item.Type), courseLibraryModeLabel(item.Mode),
|
||||
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatedAt.Format("2006-01-02 15:04")}
|
||||
for i, v := range values {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, r+2)
|
||||
_ = f.SetCellValue(sheet, cell, v)
|
||||
}
|
||||
}
|
||||
buf, err := f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
filename := fmt.Sprintf("course_library_%s.xlsx", time.Now().Format("20060102150405"))
|
||||
logger.Infof(ctx, "[Training] course library exported, tenant=%d rows=%d", tenantID, len(items))
|
||||
return filename, buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key,不入知识库
|
||||
// 解析链路;名称登记与文件可并存)。
|
||||
func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
if fh == nil {
|
||||
return nil, werrors.NewBadRequestError("缺少上传文件")
|
||||
}
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return nil, werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
fileKey, err := s.fileSvc.SaveFile(ctx, fh, tenantID, "")
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to save course library material, error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
item.FileKey = fileKey
|
||||
item.FileName = fh.Filename
|
||||
item.FileSize = fh.Size
|
||||
// 文档类课件同步知识库「企业培训(课件)」(000153:AI 出题与对话问答依赖
|
||||
// 知识库分块;视频类仍只存原始文件)。同步失败 fail-open,退回原始文件存取。
|
||||
if !isVideoMaterialFile("", fh.Filename) {
|
||||
coursewareKB, _, kbErr := s.ensureTrainingKnowledgeBases(ctx)
|
||||
if kbErr != nil {
|
||||
logger.Warnf(ctx, "Skip syncing course library material to knowledge base (ensure failed): %v", kbErr)
|
||||
} else if knowledgeID, syncErr := s.syncFileToKnowledgeBase(ctx, coursewareKB.ID, fh, ""); syncErr != nil {
|
||||
logger.Warnf(ctx, "Skip syncing course library material to knowledge base (upload failed): %v", syncErr)
|
||||
} else {
|
||||
item.KnowledgeID = knowledgeID
|
||||
}
|
||||
} else {
|
||||
item.KnowledgeID = ""
|
||||
}
|
||||
// 名称登记为空时以文件名兜底,便于列表直接识别课件。
|
||||
if strings.TrimSpace(item.MaterialName) == "" {
|
||||
item.MaterialName = fh.Filename
|
||||
}
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "[Training] course library material uploaded, tenant=%d course=%s size=%d uploader=%s", tenantID, id, fh.Size, updaterID)
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// GetCourseLibraryMaterialFile 流式取回课件原始文件:文档类优先按知识库文档
|
||||
// 取回流(000153 同步入库后与月计划课件同口径),视频/同步失败回退 file_key。
|
||||
func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error) {
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return nil, "", werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if item.FileKey == "" && item.KnowledgeID == "" {
|
||||
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
|
||||
}
|
||||
if item.KnowledgeID != "" {
|
||||
rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, item.KnowledgeID)
|
||||
if err == nil {
|
||||
// 下载文件名沿用登记名(知识库文档名可能与登记名不一致)。
|
||||
return rc, item.FileName, nil
|
||||
}
|
||||
logger.Warnf(ctx, "Fallback to raw file for course library material, course: %s, error: %v", id, err)
|
||||
}
|
||||
if item.FileKey == "" {
|
||||
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
|
||||
}
|
||||
rc, err := s.fileSvc.GetFile(ctx, item.FileKey)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return rc, item.FileName, nil
|
||||
}
|
||||
|
||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
|
||||
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
|
||||
// 原始文件字段清空,名称登记为空时以文档名兜底。
|
||||
func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
knowledgeID = strings.TrimSpace(knowledgeID)
|
||||
if knowledgeID == "" {
|
||||
return nil, werrors.NewBadRequestError("缺少知识库文档")
|
||||
}
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return nil, werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
doc, docErr := s.knowledgeSvc.GetKnowledgeByID(ctx, knowledgeID)
|
||||
if docErr != nil || doc == nil {
|
||||
return nil, werrors.NewNotFoundError("知识库文档不存在")
|
||||
}
|
||||
name := strings.TrimSpace(doc.FileName)
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(doc.Title)
|
||||
}
|
||||
if name != "" {
|
||||
item.FileName = name
|
||||
if strings.TrimSpace(item.MaterialName) == "" {
|
||||
item.MaterialName = name
|
||||
}
|
||||
}
|
||||
item.FileKey, item.FileSize = "", 0
|
||||
item.KnowledgeID = knowledgeID
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "[Training] course library material attached from knowledge base, tenant=%d course=%s knowledge=%s operator=%s", tenantID, id, knowledgeID, updaterID)
|
||||
return item, nil
|
||||
}
|
||||
@@ -171,6 +171,9 @@ func defaultRuleSeed() map[string]string {
|
||||
roleDictRaw, _ := json.Marshal(map[string]any{"roles": types.DefaultRoleDict()})
|
||||
// [2026-11 需求] 提醒推送文案默认模板(配置中心「提醒推送文案」卡)
|
||||
notifyTextRaw, _ := json.Marshal(defaultNotifyTextTemplates())
|
||||
// [2026-11 需求] 课程分类默认字典(配置中心「课程分类」卡;课程管理
|
||||
// 筛选/表单下拉选项,缺失时前端有同值兜底)
|
||||
categoryDictRaw, _ := json.Marshal(map[string]any{"categories": types.DefaultCourseCategories()})
|
||||
return map[string]string{
|
||||
types.RuleKeyLecturerScoreWeight: `{"on_time":40,"rating":50,"qa":10}`,
|
||||
types.RuleKeyPointRules: `{"required":10,"score_90":10,"score_100":20,"pass":5,"elective":5,"self_study":3}`,
|
||||
@@ -179,6 +182,7 @@ func defaultRuleSeed() map[string]string {
|
||||
types.RuleKeyPassLine: `{"default":75}`,
|
||||
types.RuleKeyRollPolicy: `{"escalate_after":2}`,
|
||||
types.RuleKeyRoleDict: string(roleDictRaw),
|
||||
types.RuleKeyCourseCategoryDict: string(categoryDictRaw),
|
||||
ruleKeyNotifyRemindDays: `[3,1]`,
|
||||
ruleKeyNotifyPushEnabled: `true`,
|
||||
ruleKeyNotifyWeeklyLecturer: `{"enabled":true,"hour":9}`,
|
||||
|
||||
@@ -46,12 +46,6 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
|
||||
if s.chunkSvc == nil || s.models == nil {
|
||||
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
|
||||
}
|
||||
if count <= 0 {
|
||||
count = 10
|
||||
}
|
||||
if count > 30 {
|
||||
count = 30
|
||||
}
|
||||
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
|
||||
if err != nil || material == nil {
|
||||
return nil, errors.NewNotFoundError("课件不存在")
|
||||
@@ -62,21 +56,50 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
|
||||
if material.KnowledgeID == "" {
|
||||
return nil, errors.NewBadRequestError("该课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
|
||||
}
|
||||
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, material.KnowledgeID, material.Name, count)
|
||||
}
|
||||
|
||||
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(000153):读取课程管理
|
||||
// 条目课件同步知识库后的分块文本出题;题目不落库,预览确认后经
|
||||
// ImportGeneratedQuestionBank 建库并挂 library_course_id。
|
||||
func (s *trainingService) GenerateLibraryCourseQuestions(ctx context.Context, tenantID uint64, userID, libraryCourseID string, count int) ([]*types.TrainingQuestion, error) {
|
||||
if s.chunkSvc == nil || s.models == nil {
|
||||
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
|
||||
}
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, libraryCourseID)
|
||||
if err != nil || item == nil {
|
||||
return nil, errors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if item.KnowledgeID == "" {
|
||||
return nil, errors.NewBadRequestError("该课程课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
|
||||
}
|
||||
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, item.KnowledgeID, item.Name, count)
|
||||
}
|
||||
|
||||
// generateQuestionsFromKnowledge 按知识库文档分块拼上下文并交默认模型出题
|
||||
// (GenerateCourseQuestions / GenerateLibraryCourseQuestions 共用管线)。
|
||||
func (s *trainingService) generateQuestionsFromKnowledge(ctx context.Context, tenantID uint64, userID, knowledgeID, sourceName string, count int) ([]*types.TrainingQuestion, error) {
|
||||
if count <= 0 {
|
||||
count = 10
|
||||
}
|
||||
if count > 30 {
|
||||
count = 30
|
||||
}
|
||||
// 拼接课件的知识库文本分块,截断到 ~12k 字符控制 token。
|
||||
// 兜底:knowledge_id 悬空(知识库文档被删除/重建导致引用失效)时,
|
||||
// 按课件名在「企业培训(课件)」知识库找同名文档取分块,避免旧引用卡死出题。
|
||||
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, material.KnowledgeID)
|
||||
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, knowledgeID)
|
||||
if chunkErr != nil || len(chunks) == 0 {
|
||||
if altID := s.findCoursewareKnowledgeIDByName(ctx, material.Name); altID != "" {
|
||||
if altID := s.findCoursewareKnowledgeIDByName(ctx, sourceName); altID != "" {
|
||||
if altChunks, altErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, altID); altErr == nil && len(altChunks) > 0 {
|
||||
material.KnowledgeID = altID
|
||||
knowledgeID = altID
|
||||
chunks = altChunks
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(chunks) == 0 {
|
||||
return nil, errors.NewBadRequestError(
|
||||
"课件文本索引缺失(知识库分块已被清理),请在知识库中对该文档「重新解析」,或在课程详情重新上传课件后再试")
|
||||
"课件文本索引缺失(知识库分块已被清理),请在知识库中对该文档「重新解析」,或重新上传课件后再试")
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, c := range chunks {
|
||||
@@ -100,7 +123,7 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
|
||||
}
|
||||
llmCtx, cancel := context.WithTimeout(ctx, aiQuestionGenTimeout)
|
||||
defer cancel()
|
||||
llmCtx = types.WithLLMCallMetadata(llmCtx, "training.course_question_gen", material.KnowledgeID)
|
||||
llmCtx = types.WithLLMCallMetadata(llmCtx, "training.course_question_gen", knowledgeID)
|
||||
thinking := false
|
||||
response, err := model.Chat(llmCtx, []chat.Message{
|
||||
{Role: "system", Content: aiQuestionSystemPrompt()},
|
||||
@@ -114,7 +137,7 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
|
||||
logger.Warnf(ctx, "[training] ai question gen llm call failed: %v", err)
|
||||
return nil, errors.NewBadRequestError("大模型调用失败:" + aiErrBrief(err))
|
||||
}
|
||||
return parseAIQuestions(response.Content, material.Name)
|
||||
return parseAIQuestions(response.Content, sourceName)
|
||||
}
|
||||
|
||||
// findCoursewareKnowledgeIDByName 在「企业培训(课件)」知识库按标题/文件名
|
||||
@@ -212,9 +235,9 @@ func extractJSONBracket(content string, open, close byte) string {
|
||||
}
|
||||
|
||||
// ImportGeneratedQuestionBank 使用(AI 生成并经人工编辑的)题目建题库:
|
||||
// 关联课程;题目以分节文本同步进「企业培训(题库)」知识库(检索与 AI 问答可用);
|
||||
// 未指定课程时继承同名旧题库的课程关联,同名旧库会被替换。
|
||||
func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
// 关联课程/课程管理条目;题目以分节文本同步进「企业培训(题库)」知识库(检索与
|
||||
// AI 问答可用);未指定归属时继承同名旧题库的关联,同名旧库会被替换。
|
||||
func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, libraryCourseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) {
|
||||
if len(questions) == 0 {
|
||||
return nil, errors.NewBadRequestError("题目为空")
|
||||
}
|
||||
@@ -222,15 +245,18 @@ func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenan
|
||||
if name == "" {
|
||||
name = "AI生成题库"
|
||||
}
|
||||
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if courseID == "" {
|
||||
courseID = oldCourseID
|
||||
}
|
||||
if libraryCourseID == "" {
|
||||
libraryCourseID = oldLibraryCourseID
|
||||
}
|
||||
knowledgeID := s.syncQuestionsToBankKB(ctx, questions, name)
|
||||
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, KnowledgeID: knowledgeID}
|
||||
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID}
|
||||
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,21 +3,26 @@ package service
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/assets/trainingtemplates"
|
||||
"academy/internal/errors"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 配置中心 · 导入模板管理:
|
||||
// 模板按业务键(demand_collection/question_bank)管理,租户上传的自定义版本存
|
||||
// tr_templates 并全端生效;未上传或「恢复默认」后下载回退二进制内置文件
|
||||
// (internal/assets/trainingtemplates,源 docs/moban)。
|
||||
// 模板按业务键(demand_collection/question_bank/course_library)管理,租户上传的
|
||||
// 自定义版本存 tr_templates 并全端生效;未上传或「恢复默认」后下载回退二进制
|
||||
// 内置文件(internal/assets/trainingtemplates,源 docs/moban)。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// templateMaxSize 模板 Excel 上限(10MB,业务模板均为几十 KB 级,防误传大文件)。
|
||||
@@ -26,19 +31,21 @@ const templateMaxSize = 10 << 20
|
||||
// ListTrainingTemplates returns metadata of all managed templates,
|
||||
// merging tenant custom versions over bundled defaults.
|
||||
func (s *trainingService) ListTrainingTemplates(ctx context.Context, tenantID uint64) ([]*types.TrainingTemplateMeta, error) {
|
||||
keys := []string{
|
||||
types.TrainingTemplateDemandCollection,
|
||||
types.TrainingTemplateQuestionBank,
|
||||
types.TrainingTemplateCourseLibrary,
|
||||
}
|
||||
customs := map[string]*types.TrainingTemplate{}
|
||||
if tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, types.TrainingTemplateDemandCollection); err != nil {
|
||||
return nil, err
|
||||
} else if tpl != nil {
|
||||
customs[tpl.TemplateKey] = tpl
|
||||
for _, key := range keys {
|
||||
tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tpl != nil {
|
||||
customs[tpl.TemplateKey] = tpl
|
||||
}
|
||||
}
|
||||
if tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, types.TrainingTemplateQuestionBank); err != nil {
|
||||
return nil, err
|
||||
} else if tpl != nil {
|
||||
customs[tpl.TemplateKey] = tpl
|
||||
}
|
||||
|
||||
keys := []string{types.TrainingTemplateDemandCollection, types.TrainingTemplateQuestionBank}
|
||||
out := make([]*types.TrainingTemplateMeta, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
meta := &types.TrainingTemplateMeta{
|
||||
@@ -65,7 +72,8 @@ func (s *trainingService) ListTrainingTemplates(ctx context.Context, tenantID ui
|
||||
|
||||
// TrainingTemplateFile resolves the effective template bytes:
|
||||
// tenant custom version first, bundled default otherwise.
|
||||
// 收集模板(demand_collection)在返回前注入组织架构下拉(见 enrichDemandTemplate)。
|
||||
// 收集模板(demand_collection)在返回前动态注入下拉与年份(见 enrichDemandTemplate);
|
||||
// 课程管理模板(course_library)在返回前动态注入下拉(见 enrichCourseLibraryTemplate)。
|
||||
func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uint64, key string) ([]byte, string, error) {
|
||||
if !trainingtemplates.IsKnown(key) {
|
||||
return nil, "", errors.NewBadRequestError("未知模板类型")
|
||||
@@ -86,8 +94,11 @@ func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uin
|
||||
return nil, "", errors.NewBadRequestError("模板文件缺失")
|
||||
}
|
||||
}
|
||||
if key == types.TrainingTemplateDemandCollection {
|
||||
switch key {
|
||||
case types.TrainingTemplateDemandCollection:
|
||||
data = s.enrichDemandTemplate(ctx, tenantID, data)
|
||||
case types.TrainingTemplateCourseLibrary:
|
||||
data = s.enrichCourseLibraryTemplate(ctx, tenantID, data)
|
||||
}
|
||||
return data, fileName, nil
|
||||
}
|
||||
@@ -95,21 +106,38 @@ func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uin
|
||||
// demandTemplateOptionCols 收集模板下拉辅助列(明细表内右侧隐藏列,
|
||||
// 同表引用规避跨表公式与 255 字符内联列表限制)。
|
||||
const (
|
||||
demandOptColDept = "CA" // 部门单位(组织架构部门)
|
||||
demandOptColJoin = "CB" // 参加人员(员工档案)
|
||||
demandOptColLect = "CC" // 培训讲师(员工档案)
|
||||
demandTargetRows = 500 // 下拉覆盖的数据行数(第 4~503 行)
|
||||
demandMemberLimit = 2000 // 员工档案下拉取值上限
|
||||
demandOptColDept = "CA" // 部门单位(组织架构部门)
|
||||
demandOptColLect = "CC" // 培训讲师(员工档案)
|
||||
// 课程联动查找表(000156):CE=课程名称 CF=所属部门 CG=适合人员 CH=讲师,
|
||||
// 按部门分组排序;C 列下拉经 OFFSET+MATCH 联动 B 列所选部门,D/I 列
|
||||
// VLOOKUP 自动带出该课程的适合人员/讲师(可改写,改后按填写值导入)。
|
||||
demandLookupColName = "CE"
|
||||
demandLookupColDept = "CF"
|
||||
demandLookupColSuit = "CG"
|
||||
demandLookupColLect = "CH"
|
||||
demandTargetRows = 500 // 下拉覆盖的数据行数(第 4~503 行)
|
||||
demandMemberLimit = 2000 // 员工档案下拉取值上限
|
||||
demandCourseLimit = 2000 // 课程管理下拉取值上限
|
||||
)
|
||||
|
||||
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)注入
|
||||
// 组织架构下拉:
|
||||
// - 「部门」(B 列)下拉=组织架构部门;
|
||||
// - 「参加人员」(D 列)「讲师」(I 列)下拉=员工档案人员姓名(联查 users 优先取
|
||||
// display_name 真实姓名,回退 username 工号;去重去空);
|
||||
// demandTitleYearRe 标题行年份(如「2026 年 度 教 育 训 练 需 求 表」)。
|
||||
var demandTitleYearRe = regexp.MustCompile(`20\d{2}`)
|
||||
|
||||
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)动态注入:
|
||||
// - 标题年份改为下一年度(收集模板面向下年度计划,如 2026 年下载即 2027);
|
||||
// - 「计划培训时间」(H 列)表头改为「计划培训月份」,下拉=1~12 月;
|
||||
// - 「参加人员」(D 列)表头归一为「适合人员」(000154 新口径,兼容旧自定义模板);
|
||||
// - 「內/外培訓」(G 列)表头归一为「内/外培训」,下拉=内部/外部;
|
||||
// - 「课程名称」(C 列)下拉按 B 列所选部门联动(OFFSET+MATCH 引用课程查找表,
|
||||
// 仅列该部门课程;非阻断式,也可直接填写新课程);
|
||||
// - 「适合人员」(D 列)「讲师」(I 列)按所选课程 VLOOKUP 自动带出(可改写,
|
||||
// 改后按填写值导入);I 列同时保留员工档案人员下拉;
|
||||
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(I 列)下拉=员工档案人员姓名
|
||||
// (联查 users 优先取 display_name 真实姓名,回退 username 工号;去重去空)。
|
||||
//
|
||||
// 取值写入同表隐藏辅助列(CA/CB/CC),以数据验证下拉呈现(数据区 4~503 行)。
|
||||
// 基础文件不可解析(如旧 .xls 自定义版)或数据源失败时原样返回,不阻断下载。
|
||||
// 取值写入同表隐藏辅助列(CA/CC + 课程查找表 CE~CH),以数据验证/公式呈现
|
||||
// (数据区 4~503 行)。基础文件不可解析(如旧 .xls 自定义版)或数据源失败时
|
||||
// 原样返回,不阻断下载。
|
||||
func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uint64, base []byte) []byte {
|
||||
f, err := excelize.OpenReader(bytes.NewReader(base))
|
||||
if err != nil {
|
||||
@@ -121,7 +149,33 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
sheet := sheets[0]
|
||||
|
||||
// 下拉取值:组织架构部门 + 员工档案人员(去重、去空)
|
||||
// 标题年份:面向下一年度收集(2026 年打开即 2027 年度教育训练需求表)。
|
||||
// 标题合并于 B1:J1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
|
||||
nextYear := time.Now().Year() + 1
|
||||
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"} {
|
||||
val, _ := f.GetCellValue(sheet, col+"1")
|
||||
if demandTitleYearRe.MatchString(val) {
|
||||
_ = f.SetCellValue(sheet, col+"1",
|
||||
demandTitleYearRe.ReplaceAllString(val, strconv.Itoa(nextYear)))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训时间」表头改「计划培训月份」(H2 合并单元格左上角取值)。
|
||||
if val, _ := f.GetCellValue(sheet, "H2"); strings.Contains(val, "计划培训时间") {
|
||||
_ = f.SetCellValue(sheet, "H2", "计划培训月份")
|
||||
}
|
||||
|
||||
// 表头归一(000154,兼容旧版自定义模板):「参加人员」D2 → 「适合人员」,
|
||||
// 「內/外培訓」G2 → 「内/外培训」(繁体转简体+新文案)。
|
||||
if val, _ := f.GetCellValue(sheet, "D2"); strings.Contains(val, "参加人员") {
|
||||
_ = f.SetCellValue(sheet, "D2", "适合人员")
|
||||
}
|
||||
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
|
||||
_ = f.SetCellValue(sheet, "G2", "内/外培训")
|
||||
}
|
||||
|
||||
// 下拉取值:组织架构部门 + 课程管理课程 + 员工档案人员(去重、去空)
|
||||
deptNames := []string{}
|
||||
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
|
||||
for _, d := range depts {
|
||||
@@ -130,6 +184,37 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
}
|
||||
}
|
||||
// 课程联动查找表(000156):按部门分组排序后写隐藏列 CE~CH,
|
||||
// 供 C 列部门联动下拉(OFFSET+MATCH)与 D/I 列自动带出(VLOOKUP)引用。
|
||||
type demandCourseRow struct{ name, dept, suitable, lecturer string }
|
||||
courseRows := []demandCourseRow{}
|
||||
if courses, _, err := s.repo.ListCourseLibrary(ctx, tenantID, &interfaces.TrainingListQuery{
|
||||
Page: 1, PageSize: demandCourseLimit,
|
||||
}); err == nil {
|
||||
for _, c := range courses {
|
||||
if c == nil || strings.TrimSpace(c.Name) == "" {
|
||||
continue
|
||||
}
|
||||
courseRows = append(courseRows, demandCourseRow{
|
||||
name: strings.TrimSpace(c.Name),
|
||||
dept: strings.TrimSpace(c.OwnerDeptName),
|
||||
suitable: strings.TrimSpace(c.SuitableMembers),
|
||||
lecturer: strings.TrimSpace(c.LecturerName),
|
||||
})
|
||||
}
|
||||
sort.SliceStable(courseRows, func(i, j int) bool {
|
||||
// 部门升序分组(未挂部门的排最后),同部门按课程名升序:
|
||||
// OFFSET+COUNTIF 联动公式要求同部门课程在查找表中连续。
|
||||
di, dj := courseRows[i].dept, courseRows[j].dept
|
||||
if (di == "") != (dj == "") {
|
||||
return di != ""
|
||||
}
|
||||
if di != dj {
|
||||
return di < dj
|
||||
}
|
||||
return courseRows[i].name < courseRows[j].name
|
||||
})
|
||||
}
|
||||
empNames := []string{}
|
||||
if members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, &types.OrgListQuery{
|
||||
Page: 1, PageSize: demandMemberLimit,
|
||||
@@ -148,10 +233,19 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
}
|
||||
|
||||
// 「适合人员」(D 列)不挂下拉(改由 VLOOKUP 自动带出,可改写);清除既有验证
|
||||
// (含历史版本注入的),避免叠加。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("D4:D%d", demandTargetRows+3))
|
||||
|
||||
// 「内/外培训」(G 列)先清既有验证再挂固定下拉,避免旧版模板叠加重复下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
// 「课程名称」(C 列)清既有验证(历史版本注入过扁平课程下拉),换部门联动下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("C4:C%d", demandTargetRows+3))
|
||||
|
||||
// 写隐藏辅助列并以数据验证下拉挂到对应列。
|
||||
// 下拉为非阻断式(ShowErrorMessage=false,NewDataValidation 默认):单元格可
|
||||
// 自由填写——参加人员可填多人(、/,分隔),讲师可填系统外姓名。
|
||||
// prompt 为选中单元格时浮出的输入提示,引导多选与外部讲师填写方式。
|
||||
// 自由填写——课程名称可选可填新课程,讲师可填系统外姓名。
|
||||
// prompt 为选中单元格时浮出的输入提示,引导填写方式。
|
||||
applyList := func(optCol, header string, values []string, targetRange string, prompt string) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
@@ -176,11 +270,72 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
}
|
||||
applyList(demandOptColDept, "部门(组织架构)", deptNames, fmt.Sprintf("B4:B%d", demandTargetRows+3), "")
|
||||
applyList(demandOptColJoin, "参加人员(员工档案)", empNames,
|
||||
fmt.Sprintf("D4:D%d", demandTargetRows+3), "可从下拉选择,也可直接填写多个姓名,用、或,分隔")
|
||||
applyList(demandOptColLect, "培训讲师(员工档案)", empNames,
|
||||
fmt.Sprintf("I4:I%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
|
||||
// 课程联动(000156):查找表写 CE~CH 隐藏列后——
|
||||
// C 列下拉 = OFFSET+MATCH 按 B 列所选部门联动该部门课程(同部门课程连续分组);
|
||||
// D 列 = VLOOKUP 带出课程「适合人员」,I 列 = 带出「讲师」;单元格可改写,
|
||||
// 改写后按填写值导入(导入解析取单元格显示值)。
|
||||
if n := len(courseRows); n > 0 {
|
||||
last := n + 1 // 查找表数据末行(表头占第 1 行)
|
||||
lookupCols := []string{demandLookupColName, demandLookupColDept, demandLookupColSuit, demandLookupColLect}
|
||||
headers := []string{"课程名称(课程管理)", "所属部门", "适合人员", "讲师"}
|
||||
for ci, col := range lookupCols {
|
||||
if err := f.SetCellValue(sheet, col+"1", headers[ci]); err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
for i, row := range courseRows {
|
||||
r := i + 2
|
||||
vals := []string{row.name, row.dept, row.suitable, row.lecturer}
|
||||
for ci, col := range lookupCols {
|
||||
_ = f.SetCellValue(sheet, fmt.Sprintf("%s%d", col, r), vals[ci])
|
||||
}
|
||||
}
|
||||
for _, col := range lookupCols {
|
||||
_ = f.SetColVisible(sheet, col, false)
|
||||
}
|
||||
// C 列部门联动下拉:OFFSET 自 CE2 偏移 MATCH(B4) 行,高度=COUNTIF 该部门课程数。
|
||||
dvCourse := excelize.NewDataValidation(true)
|
||||
dvCourse.SetSqref(fmt.Sprintf("C4:C%d", demandTargetRows+3))
|
||||
dvCourse.Type = "list"
|
||||
dvCourse.Formula1 = fmt.Sprintf(
|
||||
"OFFSET($%s$2,MATCH($B4,$%s$2:$%s$%d,0)-1,0,COUNTIF($%s$2:$%s$%d,$B4),1)",
|
||||
demandLookupColName,
|
||||
demandLookupColDept, demandLookupColDept, last,
|
||||
demandLookupColDept, demandLookupColDept, last,
|
||||
)
|
||||
dvCourse.SetInput("课程名称(按部门联动)", "先选部门,课程名称下拉即列出该部门课程;也可直接填写新课程")
|
||||
_ = f.AddDataValidation(sheet, dvCourse)
|
||||
// D/I 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
|
||||
for i := 0; i < demandTargetRows; i++ {
|
||||
r := i + 4
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("D%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,3,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("I%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,4,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训月份」(H 列)下拉=1~12(内联列表,非阻断式可自由填写)。
|
||||
dv := excelize.NewDataValidation(true)
|
||||
dv.SetSqref(fmt.Sprintf("H4:H%d", demandTargetRows+3))
|
||||
dv.Type = "list"
|
||||
dv.Formula1 = `"1,2,3,4,5,6,7,8,9,10,11,12"`
|
||||
dv.SetInput("计划培训月份", "从下拉选择 1~12 月;导入后自动按「标题年份-月份」入库(如 2027-1)")
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
|
||||
// 「内/外培训」(G 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
|
||||
dvTrain := excelize.NewDataValidation(true)
|
||||
dvTrain.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
dvTrain.Type = "list"
|
||||
dvTrain.Formula1 = `"内部,外部"`
|
||||
dvTrain.SetInput("内/外培训", "从下拉选择内部或外部;留空视为未选择")
|
||||
_ = f.AddDataValidation(sheet, dvTrain)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return base
|
||||
@@ -188,6 +343,148 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// courseLibraryTemplateOptionCols 课程管理模板下拉辅助列(同表右侧隐藏列,
|
||||
// 引用同表规避跨表公式;分类/部门名单可能超过内联列表 255 字符限制故走辅助列)。
|
||||
const (
|
||||
courseLibOptColDept = "CA" // 所属部门(组织架构部门)
|
||||
courseLibOptColCat = "CB" // 课程分类(配置中心字典)
|
||||
courseLibOptColLect = "CC" // 讲师(员工档案)
|
||||
courseLibTargetRows = 500 // 下拉覆盖的数据行数(表头在第 1 行,数据区 2~501 行)
|
||||
courseLibMemberLimit = 2000 // 员工档案下拉取值上限
|
||||
)
|
||||
|
||||
// enrichCourseLibraryTemplate 给课程管理导入模板(内置默认/自定义 xlsx 版)动态注入
|
||||
// 下拉选择(表头在第 1 行):
|
||||
// - 「所属部门」(A 列)下拉=组织架构部门;「课程分类」(E 列)下拉=配置中心
|
||||
// course_category_dict 字典(缺省回退内置 6 类);「讲师」(H 列)下拉=员工档案
|
||||
// 人员姓名(非阻断式,可直接输入外部讲师姓名);
|
||||
// - 「类型」(F 列)「线上或线下」(G 列)「课件收集」(J 列)内联列表下拉
|
||||
// (必修课/选修课、线上/线下、已有课件/暂无课件)。
|
||||
//
|
||||
// 全部下拉为非阻断式(ShowErrorMessage=false):下拉建议 + 可自由填写。
|
||||
// 基础文件不可解析(如旧 .xls 自定义版)时原样返回,不阻断下载。
|
||||
func (s *trainingService) enrichCourseLibraryTemplate(ctx context.Context, tenantID uint64, base []byte) []byte {
|
||||
f, err := excelize.OpenReader(bytes.NewReader(base))
|
||||
if err != nil {
|
||||
return base
|
||||
}
|
||||
sheets := f.GetSheetList()
|
||||
if len(sheets) == 0 {
|
||||
return base
|
||||
}
|
||||
sheet := sheets[0]
|
||||
|
||||
// 下拉取值:组织架构部门 + 课程分类字典 + 员工档案人员(去重、去空)
|
||||
deptNames := []string{}
|
||||
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
|
||||
for _, d := range depts {
|
||||
if d != nil && strings.TrimSpace(d.Name) != "" {
|
||||
deptNames = append(deptNames, strings.TrimSpace(d.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
categories := s.courseCategoryOptions(ctx, tenantID)
|
||||
empNames := []string{}
|
||||
if members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, &types.OrgListQuery{
|
||||
Page: 1, PageSize: courseLibMemberLimit,
|
||||
}); err == nil {
|
||||
seen := map[string]bool{}
|
||||
for _, m := range members {
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSpace(m.UserName)
|
||||
if name == "" || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
empNames = append(empNames, name)
|
||||
}
|
||||
}
|
||||
|
||||
applyCourseLibraryDropdowns(f, sheet, deptNames, categories, empNames)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return base
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// courseCategoryOptions 读取课程分类字典(tr_rule_configs course_category_dict;
|
||||
// 未配置或损坏时回退内置默认分类,与前端 fetchCourseCategories 同口径)。
|
||||
func (s *trainingService) courseCategoryOptions(ctx context.Context, tenantID uint64) []string {
|
||||
if cfg, err := s.repo.GetRuleConfig(ctx, tenantID, types.RuleKeyCourseCategoryDict); err == nil && cfg != nil && len(cfg.RuleValue) > 0 {
|
||||
var raw struct {
|
||||
Categories []string `json:"categories"`
|
||||
}
|
||||
if err := json.Unmarshal(cfg.RuleValue, &raw); err == nil {
|
||||
out := make([]string, 0, len(raw.Categories))
|
||||
for _, c := range raw.Categories {
|
||||
if v := strings.TrimSpace(c); v != "" {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
return types.DefaultCourseCategories()
|
||||
}
|
||||
|
||||
// applyCourseLibraryDropdowns 课程管理模板下拉注入(纯 xlsx 操作,便于单测):
|
||||
// 动态选项(部门/分类/讲师)写同表隐藏辅助列后以数据验证引用;固定选项
|
||||
// (类型/线上或线下/课件收集)用内联列表;全部非阻断式,可选可自由填写。
|
||||
func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, categories, empNames []string) {
|
||||
// 先清目标列既有验证(兼容租户上传过带验证的自定义模板),避免叠加重复下拉
|
||||
for _, col := range []string{"A", "E", "F", "G", "H", "J"} {
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1))
|
||||
}
|
||||
// 动态选项 → 隐藏辅助列 → 数据验证下拉(取值/落点/prompt 同收集模板 applyList)
|
||||
applyList := func(optCol, header string, values []string, targetRange string, prompt string) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
}
|
||||
if err := f.SetCellValue(sheet, optCol+"1", header); err != nil {
|
||||
return
|
||||
}
|
||||
for i, v := range values {
|
||||
if err := f.SetCellValue(sheet, fmt.Sprintf("%s%d", optCol, i+2), v); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = f.SetColVisible(sheet, optCol, false)
|
||||
dv := excelize.NewDataValidation(true)
|
||||
dv.SetSqref(targetRange)
|
||||
dv.Type = "list"
|
||||
dv.Formula1 = fmt.Sprintf("$%s$2:$%s$%d", optCol, optCol, len(values)+1)
|
||||
if prompt != "" {
|
||||
dv.SetInput(header, prompt)
|
||||
}
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
}
|
||||
applyList(courseLibOptColDept, "所属部门(组织架构)", deptNames,
|
||||
fmt.Sprintf("A2:A%d", courseLibTargetRows+1), "从下拉选择组织架构部门;导入后按部门名自动关联")
|
||||
applyList(courseLibOptColCat, "课程分类(配置)", categories,
|
||||
fmt.Sprintf("E2:E%d", courseLibTargetRows+1), "从下拉选择配置中心「课程分类」;分类之外可直接填写,导入后保存为自定义分类")
|
||||
applyList(courseLibOptColLect, "讲师(员工档案)", empNames,
|
||||
fmt.Sprintf("H2:H%d", courseLibTargetRows+1), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
|
||||
// 固定内联列表下拉(非阻断式可自由填写)
|
||||
inlineList := func(col, values, title, prompt string) {
|
||||
dv := excelize.NewDataValidation(true)
|
||||
dv.SetSqref(fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1))
|
||||
dv.Type = "list"
|
||||
dv.Formula1 = values
|
||||
dv.SetInput(title, prompt)
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
}
|
||||
inlineList("F", `"必修课,选修课"`, "类型", "从下拉选择必修课或选修课;留空默认必修课")
|
||||
inlineList("G", `"线上,线下"`, "线上或线下", "从下拉选择线上或线下;留空默认线下")
|
||||
inlineList("J", `"已有课件,暂无课件"`, "课件收集", "从下拉选择已有课件或暂无课件;也可直接填写课件名称")
|
||||
}
|
||||
|
||||
// SaveTrainingTemplate stores a tenant custom template (content-type validated upstream).
|
||||
func (s *trainingService) SaveTrainingTemplate(ctx context.Context, tenantID uint64, key, fileName string, data []byte, updaterID string) (*types.TrainingTemplateMeta, error) {
|
||||
if !trainingtemplates.IsKnown(key) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// 课程管理模板下拉注入(enrichCourseLibraryTemplate 的纯 xlsx 部分):
|
||||
// 部门/分类/讲师走隐藏辅助列,类型/线上或线下/课件收集内联列表,共 6 组下拉。
|
||||
func TestApplyCourseLibraryDropdowns(t *testing.T) {
|
||||
f := excelize.NewFile()
|
||||
sheet := "课程管理"
|
||||
f.SetSheetName("Sheet1", sheet)
|
||||
// 模拟内置资产表头(与 trainingtemplates.TestCourseLibraryDefaultAsset 同口径)
|
||||
for i, h := range []string{
|
||||
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
|
||||
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集",
|
||||
} {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
require.NoError(t, f.SetCellValue(sheet, cell, h))
|
||||
}
|
||||
|
||||
applyCourseLibraryDropdowns(f, sheet,
|
||||
[]string{"财务部", "技术部"},
|
||||
[]string{"专业技能类", "通用技能类"},
|
||||
[]string{"何莲", "王睿喆", "陆彦彤"})
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
f2, err := excelize.OpenReader(bytes.NewReader(buf.Bytes()))
|
||||
require.NoError(t, err)
|
||||
defer f2.Close()
|
||||
|
||||
// 6 组数据验证全部挂上(部门/分类/讲师/类型/线上或线下/课件收集)
|
||||
dvs, err := f2.GetDataValidations(sheet)
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, len(dvs), 6)
|
||||
|
||||
// 隐藏辅助列取值:CA=部门 / CB=分类 / CC=讲师
|
||||
v, err := f2.GetCellValue(sheet, "CA2")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "财务部", v)
|
||||
v, err = f2.GetCellValue(sheet, "CB2")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "专业技能类", v)
|
||||
v, err = f2.GetCellValue(sheet, "CC2")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "何莲", v)
|
||||
|
||||
// 重复注入不叠加:清旧验证后再挂,总数保持 6
|
||||
applyCourseLibraryDropdowns(f2, sheet,
|
||||
[]string{"财务部"}, []string{"专业技能类"}, []string{"何莲"})
|
||||
buf2, err := f2.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
f3, err := excelize.OpenReader(bytes.NewReader(buf2.Bytes()))
|
||||
require.NoError(t, err)
|
||||
defer f3.Close()
|
||||
dvs, err = f3.GetDataValidations(sheet)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dvs, 6)
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -4,27 +4,29 @@
|
||||
// 未上传或恢复默认时回退到本包内置文件。
|
||||
// 需求收集默认模板自 2026-11 起为公司标准「教育训练需求表模板.xlsx」
|
||||
// (原 .xls 版重制为 xlsx 并增加「计划培训时间」列):xlsx 可被 excelize
|
||||
// 解析,服务层下载时会按新布局注入组织架构部门/员工下拉
|
||||
// (training_template.go enrichDemandTemplate,部门 B/参加人员 D/讲师 I)。
|
||||
// 解析,服务层下载时会按新布局注入组织架构部门/员工下拉与表头归一
|
||||
// (training_template.go enrichDemandTemplate,部门 B/适合人员 D/内/外培训 G/讲师 I)。
|
||||
package trainingtemplates
|
||||
|
||||
import (
|
||||
"embed"
|
||||
)
|
||||
|
||||
//go:embed demand_collection.xlsx question_bank.xlsx
|
||||
//go:embed demand_collection.xlsx question_bank.xlsx course_library.xlsx
|
||||
var files embed.FS
|
||||
|
||||
// defaultNames 内置默认文件的业务名(展示给用户,与 docs/moban 原名一致)。
|
||||
var defaultNames = map[string]string{
|
||||
"demand_collection": "教育训练需求表模板.xlsx",
|
||||
"question_bank": "部门培训课程试题(题库导入版)模板.xlsx",
|
||||
"course_library": "课程管理导入模板.xlsx",
|
||||
}
|
||||
|
||||
// assetNames 内置资产文件名(ASCII,go:embed 友好)。
|
||||
var assetNames = map[string]string{
|
||||
"demand_collection": "demand_collection.xlsx",
|
||||
"question_bank": "question_bank.xlsx",
|
||||
"course_library": "course_library.xlsx",
|
||||
}
|
||||
|
||||
// IsKnown reports whether key is a managed template key.
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package trainingtemplates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// 2026-11 需求收集默认模板为公司标准「教育训练需求表模板.xlsx」
|
||||
// (原 .xls 重制为 xlsx 并增加「计划培训时间」列),防止资产缺失或损坏。
|
||||
// 表头锁定导入/展示口径(000154):适合人员(D)/内/外培训(G);改动表头须
|
||||
// 同步 PlanPanel onImportDemandExcel 列名与 enrichDemandTemplate 表头归一。
|
||||
func TestDemandCollectionDefaultAsset(t *testing.T) {
|
||||
name, ok := DefaultFileName("demand_collection")
|
||||
require.True(t, ok)
|
||||
@@ -19,7 +23,48 @@ func TestDemandCollectionDefaultAsset(t *testing.T) {
|
||||
// zip 魔数(PK\x03\x04)= xlsx 容器
|
||||
require.Equal(t, []byte{0x50, 0x4b, 0x03, 0x04}, data[:4])
|
||||
|
||||
// 表头行(第 2 行,首行为标题合并单元格)与前端导入解析口径一致
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
rows, err := f.GetRows("需求表")
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, len(rows), 2)
|
||||
require.Equal(t, []string{
|
||||
"编号", "部门", "课程名称", "适合人员", "地 点", "培訓費用(RMB)",
|
||||
"内/外培训", "计划培训时间", "讲师", "备注",
|
||||
}, rows[1])
|
||||
|
||||
require.True(t, IsKnown("demand_collection"))
|
||||
require.True(t, IsKnown("question_bank"))
|
||||
require.True(t, IsKnown("course_library"))
|
||||
require.False(t, IsKnown("other"))
|
||||
}
|
||||
|
||||
// 课程管理默认模板(000151):表头行 = 导入解析口径(所属部门/课程名称/
|
||||
// 课程说明/适合人员/课程分类/类型(必修课或选修课)/线上或线下/讲师/
|
||||
// 时长(学时)/课件收集;仅表头无示例行,防止示例被误导入),防止资产缺失或损坏。
|
||||
// 下载时服务层会动态注入下拉(enrichCourseLibraryTemplate),内置资产只含表头。
|
||||
func TestCourseLibraryDefaultAsset(t *testing.T) {
|
||||
name, ok := DefaultFileName("course_library")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "课程管理导入模板.xlsx", name)
|
||||
|
||||
data, err := Default("course_library")
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, len(data), 1000)
|
||||
// zip 魔数(PK\x03\x04)= xlsx 容器
|
||||
require.Equal(t, []byte{0x50, 0x4b, 0x03, 0x04}, data[:4])
|
||||
|
||||
// 表头行与导入解析口径一致(改动表头须同步 LibraryPanel onImportExcel 列名)
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
rows, err := f.GetRows("课程管理")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, rows)
|
||||
require.Equal(t, []string{
|
||||
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
|
||||
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集",
|
||||
}, rows[0])
|
||||
}
|
||||
@@ -157,8 +157,9 @@ func (h *Handler) callerDataScope(c *gin.Context) (dataScope, *types.TrainingMem
|
||||
}
|
||||
}
|
||||
|
||||
// callerDeptScope 计划类列表的部门范围限定:纯课长(有课长角色、无人事/经理
|
||||
// 全局视角)只能查询本部门数据,返回其所在部门 ID;其余角色返回空串(不限定)。
|
||||
// callerDeptScope 计划类列表的部门范围限定:人事/空间管理员为全局视角(返回
|
||||
// 空串不限定);经理/课长(含继承课长的自定义角色)只能查询本部门数据,返回其
|
||||
// 所在部门 ID;其余角色(讲师/学员)不限定(本就无管理入口)。
|
||||
func (h *Handler) callerDeptScope(c *gin.Context) string {
|
||||
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
|
||||
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
|
||||
@@ -169,12 +170,14 @@ func (h *Handler) callerDeptScope(c *gin.Context) string {
|
||||
return ""
|
||||
}
|
||||
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
|
||||
if types.HasTrainingRole(roles, types.TrainingRoleHR) ||
|
||||
types.HasTrainingRole(roles, types.TrainingRoleManager) ||
|
||||
!types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
|
||||
// 人事全量;经理继承课长权限组,与课长一致收窄本部门
|
||||
if types.HasTrainingRole(roles, types.TrainingRoleHR) {
|
||||
return ""
|
||||
}
|
||||
return member.DeptID
|
||||
if types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
|
||||
return member.DeptID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// checkCourseVisibility 课程详情可见性:全局视角与已发布课程对所有人开放;
|
||||
@@ -314,7 +317,8 @@ func (h *Handler) ImportMembers(c *gin.Context) {
|
||||
// 企微 userid(培训提醒推送目标;空串=解绑)。
|
||||
func (h *Handler) UpdateMemberWecomUserid(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
// 经理与人事同权(000159):职称角色页对经理开放。
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
@@ -341,10 +345,10 @@ func rolesToJSON(roles []string) types.JSON {
|
||||
return types.JSON(data)
|
||||
}
|
||||
|
||||
// UpdateMemberRoles PUT /training/members/:id/roles
|
||||
// UpdateMemberRoles PUT /training/members/:id/roles — 经理与人事同权(000159)。
|
||||
func (h *Handler) UpdateMemberRoles(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
@@ -391,6 +395,17 @@ func (h *Handler) ListDemands(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
|
||||
}
|
||||
|
||||
// ListDemandYears GET /training/demands/years — 需求库实际年份去重列表(降序),
|
||||
// 年度需求收集页年份下拉数据源(前端默认选中最新一年);纯课长收窄本部门口径。
|
||||
func (h *Handler) ListDemandYears(c *gin.Context) {
|
||||
years, err := h.svc.ListDemandYears(c.Request.Context(), callerTenantID(c), h.callerDeptScope(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": years})
|
||||
}
|
||||
|
||||
// saveDemandRequest is the body of POST /training/demands.
|
||||
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
|
||||
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
|
||||
@@ -485,6 +500,8 @@ func (h *Handler) SaveDemand(c *gin.Context) {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
// 需求讲师回写课程管理(000156):在线改选讲师后课程管理同步追加(fail-open)。
|
||||
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), []*types.TrainingDemand{demand})
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
|
||||
}
|
||||
|
||||
@@ -550,6 +567,7 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
||||
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName,
|
||||
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
|
||||
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
|
||||
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
|
||||
TargetCount: item.TargetCount, Hours: item.Hours, ExpectMonth: item.ExpectMonth,
|
||||
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
|
||||
})
|
||||
@@ -559,22 +577,57 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result)}})
|
||||
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
|
||||
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
|
||||
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
|
||||
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}})
|
||||
}
|
||||
|
||||
// ConfirmDemand POST /training/demands/:id/confirm — 人事复核确认。
|
||||
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
|
||||
// 仅「需求归属部门」内、职称角色为经理的成员可确认,其余人员一律提示联系部门经理。
|
||||
const demandConfirmDenied = "暂无权限,请联系部门经理~"
|
||||
|
||||
// ConfirmDemand POST /training/demands/:id/confirm — 经理核验确认(部门+角色双校验)。
|
||||
// 仅「需求归属部门的成员且职称角色为经理」可核验(000154 收窄:人事/空间管理员/
|
||||
// 其他部门经理一律拒绝),统一提示「暂无权限,请联系部门经理~」;
|
||||
// 部门校验先于确认落库,避免越权时已改状态。
|
||||
func (h *Handler) ConfirmDemand(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
tenantID, userID := callerTenantID(c), callerUserID(c)
|
||||
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
demand, err := h.svc.ConfirmDemand(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
|
||||
if member == nil {
|
||||
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
|
||||
return
|
||||
}
|
||||
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList())
|
||||
if !types.HasTrainingRole(roles, types.TrainingRoleManager) {
|
||||
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
|
||||
return
|
||||
}
|
||||
existing, err := h.svc.GetDemand(ctx, tenantID, c.Param("id"))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
// 本部门口径:仅可核验本部门需求(部门缺失的需求先由人事/提报人补全部门)。
|
||||
if existing.DeptID == "" || existing.DeptID != member.DeptID {
|
||||
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
|
||||
return
|
||||
}
|
||||
demand, err := h.svc.ConfirmDemand(ctx, tenantID, c.Param("id"), userID)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
// 已确认需求自动生成草稿课程到课程管理(fail-open,不阻断确认)。
|
||||
h.syncDemandCourse(ctx, callerTenantID(c), demand, callerUserID(c))
|
||||
h.syncDemandCourse(ctx, tenantID, demand, userID)
|
||||
// 确认转月培训计划后自动推送讲师与部门课长维护(000157,站内+企微,fail-open)。
|
||||
h.notifyDemandConfirmed(ctx, tenantID, userID, demand)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
|
||||
}
|
||||
|
||||
@@ -601,12 +654,25 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
|
||||
DeptIDs: sliceToJSON([]string{demand.DeptID}),
|
||||
PostScope: demand.PostScope,
|
||||
}
|
||||
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
|
||||
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
|
||||
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
|
||||
course.SourceDemandID = demand.ID
|
||||
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
|
||||
for _, item := range libItems {
|
||||
if item != nil && item.Name == demand.CourseName {
|
||||
course.LibraryCourseID = item.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// 授课时间默认取需求「期望月份」(YYYY-MM,课程管理侧可修改并留版本记录)。
|
||||
if demand.Year > 0 && demand.ExpectMonth >= 1 && demand.ExpectMonth <= 12 {
|
||||
course.TeachTime = fmt.Sprintf("%04d-%02d", demand.Year, demand.ExpectMonth)
|
||||
}
|
||||
// 计划培训时间:需求已填则原样同步到课程(YYYY-MM-DD HH:mm / YYYY-MM-DD)。
|
||||
course.PlannedTime = trimSpace(demand.PlannedTime)
|
||||
// 计划培训月份:需求侧为「YYYY-M」(如 2027-1),归一为课程口径 YYYY-MM;
|
||||
// 旧日期格式(YYYY-MM-DD 等)原样同步。
|
||||
course.PlannedTime = demandPlannedMonthOf(trimSpace(demand.PlannedTime))
|
||||
// 需求录入信息全量同步(000150 补充的课程侧落点),课程详情弹窗只读回显。
|
||||
// 内/外培训、厂区、地点、培训次数、备注原样带入;外部讲师仅在无系统讲师时生效。
|
||||
externalLecturer := trimSpace(demand.LecturerExternal)
|
||||
@@ -701,6 +767,164 @@ func splitNames(raw string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// trainingDeptRoleRecipients 取指定部门具有任一目标职称角色(按权限分配展开后)
|
||||
// 的在职成员 user_id;部门为空或查询失败返回空(fail-open 供推送场景使用)。
|
||||
func (h *Handler) trainingDeptRoleRecipients(ctx context.Context, tenantID uint64, deptID string, want ...types.TrainingRole) []string {
|
||||
if deptID == "" {
|
||||
return nil
|
||||
}
|
||||
members, _, err := h.svc.ListMembers(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := []string{}
|
||||
for _, m := range members {
|
||||
if m == nil || m.DeptID != deptID || m.UserID == "" {
|
||||
continue
|
||||
}
|
||||
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, m.TrainingRoleList())
|
||||
for _, w := range want {
|
||||
if types.HasTrainingRole(roles, w) {
|
||||
out = append(out, m.UserID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// notifyDemandVerify 需求导入后自动推送(000157):按部门聚合,站内+企微通知
|
||||
// 该部门经理(职称角色经理)进行核实【确认】;fail-open 不阻断导入。
|
||||
// 返回成功送达的通知数(写入导入响应,前端提示)。
|
||||
func (h *Handler) notifyDemandVerify(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand) int {
|
||||
byDept := map[string][]string{}
|
||||
year := 0
|
||||
for _, d := range demands {
|
||||
if d == nil || d.DeptID == "" || trimSpace(d.CourseName) == "" {
|
||||
continue
|
||||
}
|
||||
byDept[d.DeptID] = append(byDept[d.DeptID], trimSpace(d.CourseName))
|
||||
if d.Year > 0 && year == 0 {
|
||||
year = d.Year
|
||||
}
|
||||
}
|
||||
if len(byDept) == 0 {
|
||||
return 0
|
||||
}
|
||||
deptNames := map[string]string{}
|
||||
if depts, err := h.svc.ListDepts(ctx, tenantID); err == nil {
|
||||
for _, d := range depts {
|
||||
if d != nil {
|
||||
deptNames[d.ID] = d.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
sent := 0
|
||||
for deptID, courses := range byDept {
|
||||
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, deptID, types.TrainingRoleManager)
|
||||
if len(recipients) == 0 {
|
||||
continue
|
||||
}
|
||||
name := deptNames[deptID]
|
||||
if name == "" {
|
||||
name = deptID
|
||||
}
|
||||
title := fmt.Sprintf("【年度培训需求核验】%d年度 %s 培训需求待核验", year, name)
|
||||
content := fmt.Sprintf(
|
||||
"%s 新导入 %d 条年度培训需求(课程:%s)。请登录 AIDO → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。",
|
||||
name, len(courses), strings.Join(courses, "、"),
|
||||
)
|
||||
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year))
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to notify dept managers for demand verify", err)
|
||||
continue
|
||||
}
|
||||
sent += n
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
// notifyDemandConfirmed 需求确认转月培训计划后自动推送(000157):站内+企微通知
|
||||
// 该课程讲师与部门课长维护培训相关信息(讲师维护课程信息,课长安排授课计划);
|
||||
// 确认操作人自身不重复通知;fail-open 不阻断确认。
|
||||
func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, operatorID string, demand *types.TrainingDemand) {
|
||||
if demand == nil {
|
||||
return
|
||||
}
|
||||
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, demand.DeptID, types.TrainingRoleSupervisor)
|
||||
recipients = append(recipients, trimSpace(demand.LecturerID))
|
||||
seen := map[string]bool{}
|
||||
final := []string{}
|
||||
for _, uid := range recipients {
|
||||
if uid == "" || uid == operatorID || seen[uid] {
|
||||
continue
|
||||
}
|
||||
seen[uid] = true
|
||||
final = append(final, uid)
|
||||
}
|
||||
if len(final) == 0 {
|
||||
return
|
||||
}
|
||||
title := fmt.Sprintf("【培训计划维护】%s 已确认转入月培训计划", demand.CourseName)
|
||||
content := fmt.Sprintf(
|
||||
"%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:AIDO → 企业培训 → 月培训计划。",
|
||||
demand.Year, demand.CourseName,
|
||||
)
|
||||
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID); err != nil {
|
||||
logger.Error(ctx, "Failed to notify lecturer and supervisors after demand confirm", err)
|
||||
}
|
||||
}
|
||||
|
||||
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
|
||||
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
|
||||
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
|
||||
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
|
||||
byName := map[string]*types.TrainingDemand{}
|
||||
for _, d := range demands {
|
||||
if d == nil || trimSpace(d.CourseName) == "" {
|
||||
continue
|
||||
}
|
||||
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := byName[d.CourseName]; !ok {
|
||||
byName[d.CourseName] = d
|
||||
}
|
||||
}
|
||||
if len(byName) == 0 {
|
||||
return
|
||||
}
|
||||
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to list course library for lecturer sync", err)
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
d, ok := byName[item.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
|
||||
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
|
||||
continue
|
||||
}
|
||||
updated := *item
|
||||
updated.LecturerID = lecturerID
|
||||
updated.LecturerExternal = lecturerExt
|
||||
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
|
||||
logger.Error(ctx, "Failed to sync demand lecturer to course library", err)
|
||||
continue
|
||||
}
|
||||
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
|
||||
if err := h.svc.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
|
||||
logger.Error(ctx, "Failed to ensure lecturer role on demand sync", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateAnnualPlan POST /training/annual-plans/generate — AI 汇总生成年度排期。
|
||||
func (h *Handler) GenerateAnnualPlan(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
@@ -923,6 +1147,8 @@ type saveCourseRequest struct {
|
||||
SessionCount int `json:"session_count"`
|
||||
LecturerExternal string `json:"lecturer_external"`
|
||||
Remark string `json:"remark"`
|
||||
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」选择课程后关联)。
|
||||
LibraryCourseID string `json:"library_course_id"`
|
||||
}
|
||||
|
||||
// SaveCourse POST /training/courses — 课程创建(线下/线上双向导数据源)。
|
||||
@@ -946,6 +1172,7 @@ func (h *Handler) SaveCourse(c *gin.Context) {
|
||||
PlannedTime: req.PlannedTime,
|
||||
TrainType: req.TrainType, Plant: req.Plant, Location: req.Location,
|
||||
SessionCount: req.SessionCount, LecturerExternal: req.LecturerExternal, Remark: req.Remark,
|
||||
LibraryCourseID: req.LibraryCourseID,
|
||||
}, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
@@ -1027,15 +1254,16 @@ func (h *Handler) ImportQuestionBankFromKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
KnowledgeID string `json:"knowledge_id" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
CourseID string `json:"course_id"`
|
||||
KnowledgeID string `json:"knowledge_id" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
CourseID string `json:"course_id"`
|
||||
LibraryCourseID string `json:"library_course_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
bank, err := h.svc.ImportQuestionBankFromKnowledge(ctx, callerTenantID(c), req.KnowledgeID, req.Name, req.CourseID, callerUserID(c))
|
||||
bank, err := h.svc.ImportQuestionBankFromKnowledge(ctx, callerTenantID(c), req.KnowledgeID, req.Name, req.CourseID, req.LibraryCourseID, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
@@ -1112,15 +1340,16 @@ func (h *Handler) ImportGeneratedQuestionBank(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
CourseID string `json:"course_id"`
|
||||
Name string `json:"name"`
|
||||
Questions []*types.TrainingQuestion `json:"questions" binding:"required"`
|
||||
CourseID string `json:"course_id"`
|
||||
LibraryCourseID string `json:"library_course_id"`
|
||||
Name string `json:"name"`
|
||||
Questions []*types.TrainingQuestion `json:"questions" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
bank, err := h.svc.ImportGeneratedQuestionBank(ctx, callerTenantID(c), req.CourseID, req.Name, req.Questions, callerUserID(c))
|
||||
bank, err := h.svc.ImportGeneratedQuestionBank(ctx, callerTenantID(c), req.CourseID, req.LibraryCourseID, req.Name, req.Questions, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package training
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/filetransport"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 课程管理(课程资产主数据,tr_course_library,000151)。
|
||||
// 字段:课程名称/所属部门(org_depts)/说明/适合人员/分类(配置中心
|
||||
// course_category_dict 可配,可自定义)/类型(必修课/选修课)/线上或线下/
|
||||
// 讲师/时长/课件。月培训计划的「计划名称」从本表选择。
|
||||
// 列表 Viewer 可读(月培训计划下拉同源);维护动作限人事/课长/讲师。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// saveCourseLibraryRequest is the body of POST /training/course-library.
|
||||
type saveCourseLibraryRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
OwnerDeptID string `json:"owner_dept_id"`
|
||||
Description string `json:"description"`
|
||||
SuitableMembers string `json:"suitable_members"`
|
||||
Category string `json:"category"`
|
||||
Type string `json:"type"`
|
||||
Mode string `json:"mode"`
|
||||
LecturerID string `json:"lecturer_id"`
|
||||
LecturerExternal string `json:"lecturer_external"`
|
||||
Hours float64 `json:"hours"`
|
||||
MaterialName string `json:"material_name"`
|
||||
// ClearFile 移除课件文件(前端「移除」按钮;置 true 强制清空 file_* 三列)。
|
||||
ClearFile bool `json:"clear_file"`
|
||||
}
|
||||
|
||||
// toCourseLibrary maps the request body onto the domain model.
|
||||
func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary {
|
||||
return &types.TrainingCourseLibrary{
|
||||
ID: req.ID,
|
||||
Name: req.Name,
|
||||
OwnerDeptID: req.OwnerDeptID,
|
||||
Description: req.Description,
|
||||
SuitableMembers: req.SuitableMembers,
|
||||
Category: req.Category,
|
||||
Type: req.Type,
|
||||
Mode: req.Mode,
|
||||
LecturerID: req.LecturerID,
|
||||
LecturerExternal: req.LecturerExternal,
|
||||
Hours: req.Hours,
|
||||
MaterialName: req.MaterialName,
|
||||
ClearFile: req.ClearFile,
|
||||
}
|
||||
}
|
||||
|
||||
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
||||
func (h *Handler) ListCourseLibrary(c *gin.Context) {
|
||||
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), listQueryFromRequest(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
|
||||
}
|
||||
|
||||
// SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。
|
||||
func (h *Handler) SaveCourseLibraryItem(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req saveCourseLibraryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
item, err := h.svc.SaveCourseLibraryItem(c.Request.Context(), callerTenantID(c), toCourseLibrary(req), callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除(人事/课长)。
|
||||
func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// SetCourseLibraryPublishStatus POST /training/course-library/:id/:action
|
||||
// — 课程条目发布/下线(000154;action=publish|offline,人事/课长/讲师)。
|
||||
// 发布后课程进入培训中心「和信课程」目录;下线即从目录撤回。
|
||||
func (h *Handler) SetCourseLibraryPublishStatus(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
status := ""
|
||||
switch c.Param("action") {
|
||||
case "publish":
|
||||
status = "published"
|
||||
case "offline":
|
||||
status = "offline"
|
||||
default:
|
||||
_ = c.Error(errors.NewBadRequestError("不支持的操作(仅 publish/offline)"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.SetCourseLibraryPublishStatus(c.Request.Context(), callerTenantID(c), c.Param("id"), status); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
item, err := h.svc.GetCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id"))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// ImportCourseLibraryRequest is the body of POST /training/course-library/import
|
||||
// (前端解析 Excel 后逐行提交,与需求导入同口径)。
|
||||
type ImportCourseLibraryRequest struct {
|
||||
Items []saveCourseLibraryRequest `json:"items" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// ImportCourseLibrary POST /training/course-library/import — 批量导入。
|
||||
func (h *Handler) ImportCourseLibrary(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
return
|
||||
}
|
||||
var req ImportCourseLibraryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
items := make([]*types.TrainingCourseLibrary, 0, len(req.Items))
|
||||
for _, row := range req.Items {
|
||||
items = append(items, toCourseLibrary(row))
|
||||
}
|
||||
imported, err := h.svc.ImportCourseLibraryItems(c.Request.Context(), callerTenantID(c), items, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": imported}})
|
||||
}
|
||||
|
||||
// ExportCourseLibraryRequest is the body of POST /training/course-library/export
|
||||
// (ids 空 = 全量导出;当前筛选由前端传当前列表 id)。
|
||||
type ExportCourseLibraryRequest struct {
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
|
||||
// ExportCourseLibrary POST /training/course-library/export — 课程管理 xlsx 下载。
|
||||
func (h *Handler) ExportCourseLibrary(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
return
|
||||
}
|
||||
var req ExportCourseLibraryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
filename, data, err := h.svc.ExportCourseLibrary(c.Request.Context(), callerTenantID(c), req.IDs)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Disposition", "attachment; filename="+filename)
|
||||
c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data)
|
||||
}
|
||||
|
||||
// UploadCourseLibraryMaterial POST /training/course-library/:id/material —
|
||||
// 上传课件原始文件(multipart: file)。
|
||||
func (h *Handler) UploadCourseLibraryMaterial(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
fh, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
|
||||
return
|
||||
}
|
||||
if fh.Size > utils.GetMaxFileSizeMB()*1024*1024 {
|
||||
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", utils.GetMaxFileSizeMB())))
|
||||
return
|
||||
}
|
||||
item, err := h.svc.UploadCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), fh, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// AttachCourseLibraryMaterialFromKb POST /training/course-library/:id/material/from-kb
|
||||
// — 从知识库「企业培训(课件)」选择已有文档作为课程课件(body: knowledge_id)。
|
||||
func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
KnowledgeID string `json:"knowledge_id" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
item, err := h.svc.AttachCourseLibraryMaterialFromKnowledge(c.Request.Context(), callerTenantID(c), c.Param("id"), req.KnowledgeID, callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
|
||||
// 课件原始文件流(下载/在线预览)。
|
||||
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
|
||||
rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if err := filetransport.Serve(c.Writer, c.Request, rc, filetransport.Options{Filename: fileName}); err != nil {
|
||||
_ = c.Error(err)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package training
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -36,6 +37,20 @@ func parseFlexibleTime(raw string) *time.Time {
|
||||
return nil
|
||||
}
|
||||
|
||||
// demandPlannedMonthOf 需求侧「计划培训月份」(YYYY-M,如 2027-1)归一为课程口径
|
||||
// YYYY-MM(2027-01);其余格式(旧 YYYY-MM-DD 日期等)原样返回。
|
||||
func demandPlannedMonthOf(raw string) string {
|
||||
parts := strings.SplitN(raw, "-", 2)
|
||||
if len(parts) == 2 {
|
||||
y, yErr := strconv.Atoi(strings.TrimSpace(parts[0]))
|
||||
m, mErr := strconv.Atoi(strings.TrimSpace(parts[1]))
|
||||
if yErr == nil && mErr == nil && y >= 1000 && y <= 9999 && m >= 1 && m <= 12 {
|
||||
return fmt.Sprintf("%04d-%02d", y, m)
|
||||
}
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// sliceToJSON encodes a string slice into jsonb payload.
|
||||
func sliceToJSON(items []string) types.JSON {
|
||||
if len(items) == 0 {
|
||||
@@ -79,7 +94,7 @@ func (h *Handler) ImportQuestionBankExcel(c *gin.Context) {
|
||||
}
|
||||
bank, err := h.svc.ImportQuestionBankExcel(
|
||||
ctx, callerTenantID(c),
|
||||
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), c.PostForm("course_id"),
|
||||
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), c.PostForm("course_id"), c.PostForm("library_course_id"),
|
||||
file, callerUserID(c),
|
||||
)
|
||||
if err != nil {
|
||||
@@ -209,9 +224,10 @@ func (h *Handler) SettleLecturerScores(c *gin.Context) {
|
||||
}
|
||||
|
||||
// SeedRuleConfigs POST /training/rule-configs/seed — 初始化默认规则(已存在不覆盖)。
|
||||
// 经理与人事同权(000158):配置中心对经理开放。
|
||||
func (h *Handler) SeedRuleConfigs(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
seeded, err := h.svc.SeedRuleConfigs(ctx, callerTenantID(c), callerUserID(c))
|
||||
@@ -517,7 +533,8 @@ func (h *Handler) ListRuleConfigs(c *gin.Context) {
|
||||
// SaveRuleConfig PUT /training/rule-configs/:key — 业务规则配置(人事确认后修改)。
|
||||
func (h *Handler) SaveRuleConfig(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
// 经理与人事同权(000158):配置中心对经理开放。
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
@@ -617,7 +634,8 @@ func (h *Handler) PushTestNotification(c *gin.Context) {
|
||||
// summary 带回给前端展示)。
|
||||
func (h *Handler) SyncWecomUseridsFromOA(c *gin.Context, apply bool) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
// 经理与人事同权(000159):职称角色页对经理开放。
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
summary, err := h.svc.SyncWecomUseridsFromOA(ctx, callerTenantID(c), apply)
|
||||
@@ -693,7 +711,8 @@ func (h *Handler) DownloadTrainingTemplate(c *gin.Context) {
|
||||
// UploadTrainingTemplate POST /training/templates/:key/upload — 上传自定义模板
|
||||
// (人事;校验扩展名与大小,入库后各下载入口即刻生效)。
|
||||
func (h *Handler) UploadTrainingTemplate(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
// 经理与人事同权(000158):配置中心对经理开放。
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
file, err := c.FormFile("file")
|
||||
@@ -729,7 +748,8 @@ func (h *Handler) UploadTrainingTemplate(c *gin.Context) {
|
||||
// ResetTrainingTemplate DELETE /training/templates/:key — 恢复内置默认模板
|
||||
// (人事;删除租户自定义版本,下载回退内置文件)。
|
||||
func (h *Handler) ResetTrainingTemplate(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||||
// 经理与人事同权(000158):配置中心对经理开放。
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
if err := h.svc.ResetTrainingTemplate(c.Request.Context(), callerTenantID(c), c.Param("key"), callerUserID(c)); err != nil {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package training
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 课程管理 · 试题维护(000153)
|
||||
// 试题随课程管理课程维护:课程条目下题库列表/Excel 导入/AI 出题,以及
|
||||
// 题库删除与单题级增删改查;月度计划选课后经 library_course_id 回退取卷。
|
||||
// 权限口径与课程管理一致:维护动作限人事/课长/讲师。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ListLibraryCourseQuestionBanks GET /training/course-library/:id/question-banks
|
||||
// — 课程条目下的题库列表(试题维护抽屉)。
|
||||
func (h *Handler) ListLibraryCourseQuestionBanks(c *gin.Context) {
|
||||
banks, err := h.svc.ListLibraryCourseQuestionBanks(c.Request.Context(), callerTenantID(c), c.Param("id"))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": banks})
|
||||
}
|
||||
|
||||
// ImportLibraryCourseQuestionBank POST /training/course-library/:id/question-banks/import
|
||||
// — Excel 批量导入题库并挂课程管理条目(multipart: file[name][dept_id])。
|
||||
// 同名重导入即替换;原始 Excel 自动同步「企业培训(题库)」知识库(服务层 fail-open)。
|
||||
func (h *Handler) ImportLibraryCourseQuestionBank(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
|
||||
return
|
||||
}
|
||||
bank, err := h.svc.ImportQuestionBankExcel(
|
||||
ctx, callerTenantID(c),
|
||||
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), "", c.Param("id"),
|
||||
file, callerUserID(c),
|
||||
)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": bank})
|
||||
}
|
||||
|
||||
// LinkQuestionBankToLibraryCourse PUT /training/course-library/:id/question-banks/link
|
||||
// — 更换课程条目的试题(000156):所选题库整体替换该条目当前挂接的题库,
|
||||
// 更换后自动同步到课程管理对应课程(月计划详情「试题 · 更换」入口)。
|
||||
func (h *Handler) LinkQuestionBankToLibraryCourse(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
BankID string `json:"bank_id" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := h.svc.LinkQuestionBankToLibraryCourse(ctx, callerTenantID(c), c.Param("id"), req.BankID); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
banks, err := h.svc.ListLibraryCourseQuestionBanks(ctx, callerTenantID(c), c.Param("id"))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": banks})
|
||||
}
|
||||
|
||||
// GenerateLibraryCourseQuestions POST /training/course-library/:id/generate-questions
|
||||
// — 课程管理课件 AI 出题(课件已同步知识库;预览编辑用,不落库)。
|
||||
func (h *Handler) GenerateLibraryCourseQuestions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Count int `json:"count"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
questions, err := h.svc.GenerateLibraryCourseQuestions(ctx, callerTenantID(c), callerUserID(c), c.Param("id"), req.Count)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": questions})
|
||||
}
|
||||
|
||||
// DeleteQuestionBank DELETE /training/question-banks/:id — 删除题库
|
||||
// (连带题目与缓存试卷;试题维护抽屉删除入口)。
|
||||
func (h *Handler) DeleteQuestionBank(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteQuestionBank(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// saveQuestionRequest is the body of POST /training/question-banks/:id/questions
|
||||
// (id 空 = 新增,否则编辑;题干/选项/答案等全字段)。
|
||||
type saveQuestionRequest struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Stem string `json:"stem" binding:"required"`
|
||||
Options []string `json:"options"`
|
||||
Answer string `json:"answer" binding:"required"`
|
||||
Score float64 `json:"score"`
|
||||
Difficulty int `json:"difficulty"`
|
||||
KnowledgePoint string `json:"knowledge_point"`
|
||||
Analysis string `json:"analysis"`
|
||||
}
|
||||
|
||||
// SaveQuestion POST /training/question-banks/:id/questions — 单题新增/编辑
|
||||
// (题库 question_count 同步刷新)。
|
||||
func (h *Handler) SaveQuestion(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req saveQuestionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
q, err := h.svc.SaveQuestion(c.Request.Context(), callerTenantID(c), &types.TrainingQuestion{
|
||||
ID: req.ID,
|
||||
BankID: c.Param("id"),
|
||||
Type: req.Type,
|
||||
Stem: req.Stem,
|
||||
Options: sliceToJSON(req.Options),
|
||||
Answer: req.Answer,
|
||||
Score: req.Score,
|
||||
Difficulty: req.Difficulty,
|
||||
KnowledgePoint: req.KnowledgePoint,
|
||||
Analysis: req.Analysis,
|
||||
})
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": q})
|
||||
}
|
||||
|
||||
// DeleteQuestion DELETE /training/question-banks/:id/questions/:qid — 删除单题。
|
||||
func (h *Handler) DeleteQuestion(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteQuestion(c.Request.Context(), callerTenantID(c), c.Param("qid")); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
@@ -37,6 +37,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
|
||||
// ---- 计划域:年度需求 → 年度排期 → 月度排期 ----
|
||||
trainingGroup.GET("/demands", h.ListDemands)
|
||||
// demands/years 需求库实际年份去重列表(年度筛选下拉数据源;静态段先于参数路由注册)。
|
||||
trainingGroup.GET("/demands/years", h.ListDemandYears)
|
||||
trainingGroup.POST("/demands", h.SaveDemand)
|
||||
trainingGroup.POST("/demands/import", g.Contributor(), h.ImportDemands)
|
||||
trainingGroup.POST("/demands/:id/confirm", g.Contributor(), h.ConfirmDemand)
|
||||
@@ -75,6 +77,32 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
trainingGroup.DELETE("/courses/:id", g.Contributor(), h.DeleteCourse)
|
||||
// courses/:id/exam-paper 线上自学考试取卷(确保卷存在,学员视角脱敏)。
|
||||
trainingGroup.POST("/courses/:id/exam-paper", h.CourseExamPaper)
|
||||
|
||||
// ---- 课程管理(课程资产主数据,000151;月培训计划「计划名称」数据源) ----
|
||||
trainingGroup.GET("/course-library", h.ListCourseLibrary)
|
||||
trainingGroup.POST("/course-library", g.Contributor(), h.SaveCourseLibraryItem)
|
||||
trainingGroup.DELETE("/course-library/:id", g.Contributor(), h.DeleteCourseLibraryItem)
|
||||
// 发布/下线(000154):静态段 :action 须先于 :id 参数段注册区分
|
||||
trainingGroup.POST("/course-library/:id/publish", g.Contributor(), h.SetCourseLibraryPublishStatus)
|
||||
trainingGroup.POST("/course-library/:id/offline", g.Contributor(), h.SetCourseLibraryPublishStatus)
|
||||
// 导入/导出:与需求域同口径(前端解析 Excel 后按行提交;导出 xlsx 下载)。
|
||||
trainingGroup.POST("/course-library/import", g.Contributor(), h.ImportCourseLibrary)
|
||||
trainingGroup.POST("/course-library/export", g.Contributor(), h.ExportCourseLibrary)
|
||||
// 课件原始文件(fileSvc 直存;文档类同步知识库「企业培训(课件)」,000153)。
|
||||
trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial)
|
||||
// material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。
|
||||
trainingGroup.POST("/course-library/:id/material/from-kb", g.Contributor(), h.AttachCourseLibraryMaterialFromKb)
|
||||
trainingGroup.GET("/course-library/:id/material/file", h.CourseLibraryMaterialFile)
|
||||
// ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ----
|
||||
trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks)
|
||||
// question-banks/link 更换课程条目试题(所选题库整体替换,000156;PUT 动态段与静态段共存)
|
||||
trainingGroup.PUT("/course-library/:id/question-banks/link", g.Contributor(), h.LinkQuestionBankToLibraryCourse)
|
||||
trainingGroup.POST("/course-library/:id/question-banks/import", g.Contributor(), h.ImportLibraryCourseQuestionBank)
|
||||
trainingGroup.POST("/course-library/:id/generate-questions", g.Contributor(), h.GenerateLibraryCourseQuestions)
|
||||
trainingGroup.DELETE("/question-banks/:id", g.Contributor(), h.DeleteQuestionBank)
|
||||
trainingGroup.POST("/question-banks/:id/questions", g.Contributor(), h.SaveQuestion)
|
||||
trainingGroup.DELETE("/question-banks/:id/questions/:qid", g.Contributor(), h.DeleteQuestion)
|
||||
|
||||
trainingGroup.GET("/sessions", h.ListSessions)
|
||||
trainingGroup.POST("/sessions", g.Contributor(), h.SaveSession)
|
||||
trainingGroup.GET("/sessions/:id/enrollments", h.ListEnrollments)
|
||||
|
||||
@@ -46,6 +46,8 @@ type TrainingRepository interface {
|
||||
|
||||
// ---- 需求域 ----
|
||||
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
|
||||
// ListDemandYears 需求库实际年份去重列表(降序,年份下拉数据源;deptID 非空时收窄该部门)。
|
||||
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
|
||||
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
|
||||
CreateDemand(ctx context.Context, demand *types.TrainingDemand) error
|
||||
BatchCreateDemands(ctx context.Context, demands []*types.TrainingDemand) error
|
||||
@@ -75,6 +77,16 @@ type TrainingRepository interface {
|
||||
CreateCourseChangeLog(ctx context.Context, log *types.TrainingCourseChangeLog) error
|
||||
ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error)
|
||||
|
||||
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
|
||||
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
|
||||
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
|
||||
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
||||
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
||||
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
|
||||
UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
|
||||
BatchCreateCourseLibrary(ctx context.Context, items []*types.TrainingCourseLibrary) error
|
||||
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
|
||||
|
||||
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
|
||||
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
|
||||
CreateSession(ctx context.Context, session *types.TrainingCourseSession) error
|
||||
@@ -115,24 +127,42 @@ type TrainingRepository interface {
|
||||
// UnfinishedMembers 返回某月未完成课程签到的成员(滚动/催办用)。
|
||||
UnfinishedEnrollments(ctx context.Context, tenantID uint64, year, month int) ([]*types.TrainingEnrollment, error)
|
||||
|
||||
// ---- 唯一编号(000153) ----
|
||||
// NextCodeValue 培训业务编号计数器原子递增(UPSERT ... RETURNING),
|
||||
// key 形如 AP:2026 / MP:202611 / CRS / QB,返回递增后的流水值。
|
||||
NextCodeValue(ctx context.Context, tenantID uint64, key string) (int64, error)
|
||||
|
||||
// ---- 考试域 ----
|
||||
CreateQuestionBank(ctx context.Context, bank *types.TrainingQuestionBank) error
|
||||
// ReplaceQuestionBankByName 同名题库重导入即替换(软删旧库及其题目/试卷,
|
||||
// 返回旧库课程关联供新库继承)。
|
||||
ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, error)
|
||||
// 返回旧库的课程/课程管理关联供新库继承)。
|
||||
ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, string, error)
|
||||
ListQuestionBanks(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingQuestionBank, int64, error)
|
||||
GetQuestionBank(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestionBank, error)
|
||||
// GetQuestionBankByCourse 取课程绑定的题库(线上自学考试入口)。
|
||||
GetQuestionBankByCourse(ctx context.Context, tenantID uint64, courseID string) (*types.TrainingQuestionBank, error)
|
||||
// GetQuestionBankByLibraryCourse 取课程管理条目下的题库列表(试题随课程管理维护,000153)。
|
||||
GetQuestionBankByLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error)
|
||||
// DeleteQuestionBank 软删题库及其全部题目与缓存试卷。
|
||||
DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error
|
||||
// GetSelfStudyPaperByBank 取题库的线上自学卷(session 为空、version=ONLINE)。
|
||||
GetSelfStudyPaperByBank(ctx context.Context, tenantID uint64, bankID string) (*types.TrainingPaper, error)
|
||||
UpdateQuestionBankCount(ctx context.Context, tenantID uint64, bankID string, count int) error
|
||||
// UpdateQuestionBankCourse 反向关联:建课时选择题库,把 bank.course_id 指向课程。
|
||||
UpdateQuestionBankCourse(ctx context.Context, tenantID uint64, bankID, courseID string) error
|
||||
// RelinkQuestionBankToLibraryCourse 更换课程管理条目的试题(先解挂旧库再挂新库,000156)。
|
||||
RelinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error
|
||||
|
||||
BatchCreateQuestions(ctx context.Context, questions []*types.TrainingQuestion) error
|
||||
ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error)
|
||||
ListQuestionsByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.TrainingQuestion, error)
|
||||
// 单题级维护(000153,课程管理试题抽屉)。
|
||||
CreateQuestion(ctx context.Context, question *types.TrainingQuestion) error
|
||||
GetQuestion(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestion, error)
|
||||
UpdateQuestion(ctx context.Context, question *types.TrainingQuestion) error
|
||||
DeleteQuestion(ctx context.Context, tenantID uint64, id string) error
|
||||
// CountBankQuestions 统计题库现存未删题目数(增删题目后刷新冗余计数)。
|
||||
CountBankQuestions(ctx context.Context, tenantID uint64, bankID string) (int64, error)
|
||||
|
||||
CreatePaper(ctx context.Context, paper *types.TrainingPaper) error
|
||||
GetPaper(ctx context.Context, tenantID uint64, id string) (*types.TrainingPaper, error)
|
||||
@@ -232,6 +262,8 @@ type TrainingService interface {
|
||||
|
||||
// 计划域
|
||||
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
|
||||
// ListDemandYears 需求库实际年份去重列表(降序,年份下拉数据源;deptID 非空时收窄该部门)。
|
||||
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
|
||||
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
|
||||
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
|
||||
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error)
|
||||
@@ -261,6 +293,28 @@ type TrainingService interface {
|
||||
// ListCourseChangeLogs 课程信息修改版本记录(每次保存一条,变更明细可回溯)。
|
||||
ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error)
|
||||
|
||||
// ---- 课程管理(课程资产主数据) ----
|
||||
// ListCourseLibraryItems 列表(月培训计划「计划名称」下拉数据源,Viewer 可读)。
|
||||
ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
|
||||
// SaveCourseLibraryItem 新增/编辑(id 空 = 新增)。
|
||||
SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154)。
|
||||
SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
|
||||
// GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。
|
||||
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
|
||||
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
|
||||
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后按行提交)。
|
||||
ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error)
|
||||
// ExportCourseLibrary 导出 Excel(excelize;ids 空 = 全量)。
|
||||
ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (filename string, data []byte, err error)
|
||||
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key)。
|
||||
UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
// GetCourseLibraryMaterialFile 流式取回课件原始文件。
|
||||
GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error)
|
||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
|
||||
// 已有文档作为课程课件(与上传同步同口径)。
|
||||
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
|
||||
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
|
||||
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
|
||||
ListEnrollmentsForSession(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
|
||||
@@ -303,15 +357,29 @@ type TrainingService interface {
|
||||
ImportQuestionBank(ctx context.Context, tenantID uint64, bank *types.TrainingQuestionBank, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error)
|
||||
// ImportQuestionBankExcel 解析 Excel 建题库,并把原始 Excel 同步进系统默认
|
||||
// 「企业培训(题库)」知识库(同步失败不阻断导入)。
|
||||
ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
// 知识库「企业培训(题库)」;libraryCourseID 非空时题库挂课程管理条目(000153)。
|
||||
ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID, libraryCourseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
// ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档解析建题库
|
||||
// (文档已在知识库,直接挂接 knowledge_id;未指定课程时继承同名旧库关联)。
|
||||
ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
// (同名替换,继承课程关联;libraryCourseID 非空时挂课程管理条目)。
|
||||
ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, libraryCourseID, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
// ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。
|
||||
ListLibraryCourseQuestionBanks(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error)
|
||||
// LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(所选题库整体替换,000156)。
|
||||
LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error
|
||||
// DeleteQuestionBank 删除题库(连带题目与缓存试卷)。
|
||||
DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error
|
||||
// SaveQuestion 单题新增/编辑(题库 question_count 同步刷新,000153)。
|
||||
SaveQuestion(ctx context.Context, tenantID uint64, q *types.TrainingQuestion) (*types.TrainingQuestion, error)
|
||||
// DeleteQuestion 删除单题(题库 question_count 同步刷新)。
|
||||
DeleteQuestion(ctx context.Context, tenantID uint64, questionID string) error
|
||||
// GenerateCourseQuestions AI 课件生成试题:取课件知识库分块文本交默认模型出题(不落库)。
|
||||
GenerateCourseQuestions(ctx context.Context, tenantID uint64, userID, courseID, materialID string, count int) ([]*types.TrainingQuestion, error)
|
||||
// ImportGeneratedQuestionBank 使用生成/编辑后的题目建题库(关联课程,文本同步知识库)。
|
||||
ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(读课程管理条目课件的知识库
|
||||
// 分块,出题不落库,预览确认后经 ImportGeneratedQuestionBank 建库,000153)。
|
||||
GenerateLibraryCourseQuestions(ctx context.Context, tenantID uint64, userID, libraryCourseID string, count int) ([]*types.TrainingQuestion, error)
|
||||
// ImportGeneratedQuestionBank 使用生成/编辑后的题目建题库(关联课程,文本同步知识库;
|
||||
// libraryCourseID 非空时挂课程管理条目)。
|
||||
ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, libraryCourseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
|
||||
GeneratePaper(ctx context.Context, tenantID uint64, bankID, sessionID string, count int, version, operatorID string) (*types.TrainingPaper, error)
|
||||
// GetCourseExamPaper 线上自学考试:确保课程线上卷存在并返回学员视角题目。
|
||||
GetCourseExamPaper(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingPaper, []*types.TrainingQuestion, error)
|
||||
|
||||
+98
-12
@@ -362,7 +362,9 @@ type TrainingDemand struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
Year int `json:"year" gorm:"not null;index"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
|
||||
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
|
||||
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
|
||||
@@ -535,6 +537,12 @@ type TrainingCourse struct {
|
||||
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
|
||||
// Remark 备注(需求确认同步)。
|
||||
Remark string `json:"remark" gorm:"type:text;default:''"`
|
||||
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」从课程管理选择后落此关联;可空)。
|
||||
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
|
||||
// PlanCode 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成,000153)。
|
||||
PlanCode string `json:"plan_code" gorm:"type:varchar(32);default:''"`
|
||||
// SourceDemandID 来源需求 id(经理确认自动转月度计划时回填,溯源用,000153)。
|
||||
SourceDemandID string `json:"source_demand_id" gorm:"type:varchar(36);default:''"`
|
||||
// LecturerName 讲师姓名(联查 users 只读,不落库;覆盖不在讲师名册的需求同步讲师)。
|
||||
LecturerName string `json:"lecturer_name" gorm:"->"`
|
||||
}
|
||||
@@ -557,6 +565,63 @@ type TrainingCourseChangeLog struct {
|
||||
// TableName pins the physical table name.
|
||||
func (TrainingCourseChangeLog) TableName() string { return "tr_course_change_logs" }
|
||||
|
||||
// TrainingCourseLibrary 课程管理条目(课程资产主数据,000151)。
|
||||
// 月培训计划的「计划名称」从本表选择,选中计划创建时带 library_course_id 关联。
|
||||
type TrainingCourseLibrary struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// TenantID 租户隔离。
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
// Name 课程名称(必填)。
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Code 课程编号(CRS-####,创建/导入时由服务端生成,000153)。
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
// OwnerDeptID 所属部门(org_depts id;对应需求表「主办单位」,弹窗经组织架构
|
||||
// 部门下拉选择,批量导入按部门名匹配,未匹配留空)。
|
||||
OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"`
|
||||
// Description 说明。
|
||||
Description string `json:"description" gorm:"type:text;default:''"`
|
||||
// SuitableMembers 适合人员(对应需求表「参加人员」,自由文本,如:财会人员)。
|
||||
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(255);default:''"`
|
||||
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
|
||||
Category string `json:"category" gorm:"type:varchar(64);default:''"`
|
||||
// Type 类型(required 必修课/elective 选修课)。
|
||||
Type string `json:"type" gorm:"type:varchar(16);default:'required'"`
|
||||
// Mode 形式(offline 线下/online 线上)。
|
||||
Mode string `json:"mode" gorm:"type:varchar(16);default:'offline'"`
|
||||
// LecturerID 讲师(员工 user id;与外部讲师姓名二选一)。
|
||||
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
|
||||
// LecturerExternal 外部讲师姓名(导入未匹配到员工名册时落此)。
|
||||
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
|
||||
// Hours 时长(学时)。
|
||||
Hours float64 `json:"hours" gorm:"default:0"`
|
||||
// MaterialName 课件名称登记(多个用、分隔;与文件二选一或并存)。
|
||||
MaterialName string `json:"material_name" gorm:"type:varchar(255);default:''"`
|
||||
// FileKey/FileName 课件原始文件(fileSvc 存取,可空;经专端点上传/下载)。
|
||||
FileKey string `json:"file_key" gorm:"type:varchar(512);default:''"`
|
||||
FileName string `json:"file_name" gorm:"type:varchar(255);default:''"`
|
||||
// FileSize 课件文件字节数。
|
||||
FileSize int64 `json:"file_size" gorm:"default:0"`
|
||||
// KnowledgeID 课件同步知识库「企业培训(课件)」后的文档 id(视频类留空,000153,AI 出题依赖)。
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
|
||||
// PublishStatus 发布状态(000154):draft 草稿/published 已发布/offline 已下线;
|
||||
// 培训中心「和信课程」目录仅展示已发布且部门范围覆盖查看人的课程。
|
||||
PublishStatus string `json:"publish_status" gorm:"type:varchar(16);default:'draft'"`
|
||||
// ClearFile 课件文件移除标记(请求侧瞬态,不落库:置 true 时强制清空 file_* 三列)。
|
||||
ClearFile bool `json:"clear_file" gorm:"-"`
|
||||
// CreatorID 创建人(平台用户 id)。
|
||||
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
|
||||
// LecturerName 讲师姓名(联查 users 只读,不落库)。
|
||||
LecturerName string `json:"lecturer_name" gorm:"->"`
|
||||
// OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。
|
||||
OwnerDeptName string `json:"owner_dept_name" gorm:"->"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
// TableName pins the physical table name.
|
||||
func (TrainingCourseLibrary) TableName() string { return "tr_course_library" }
|
||||
|
||||
// TrainingCourseStudyStats 课程维度的学习/考试参与成员聚合(课程管理列表状态列输入)。
|
||||
type TrainingCourseStudyStats struct {
|
||||
// SignedMembers 已签到成员(线下参与)。
|
||||
@@ -731,17 +796,21 @@ const (
|
||||
|
||||
// TrainingQuestionBank 题库。
|
||||
type TrainingQuestionBank struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
CourseID string `json:"course_id" gorm:"type:varchar(36);default:''"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
|
||||
QuestionCount int `json:"question_count" gorm:"default:0"`
|
||||
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
// Code 试题库编号(QB-####,导入/创建时由服务端生成,000153)。
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
// LibraryCourseID 课程管理条目 id(试题随课程管理维护,可与 course_id 并存,000153)。
|
||||
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
CourseID string `json:"course_id" gorm:"type:varchar(36);default:''"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
|
||||
QuestionCount int `json:"question_count" gorm:"default:0"`
|
||||
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
// TableName pins the physical table name.
|
||||
@@ -1008,8 +1077,24 @@ const (
|
||||
// RuleKeyRoleDict 职称角色字典:{"roles":[{key,label,short,system,inherits[]}]}。
|
||||
// 5 个系统角色为默认;自定义角色经 inherits 分配权限组(见 TrainingRoleDef)。
|
||||
RuleKeyRoleDict = "role_dict"
|
||||
// RuleKeyCourseCategoryDict 课程分类字典:{"categories":[...]}(课程管理
|
||||
// 筛选与表单下拉选项,配置中心「课程分类」卡维护,预设之外支持手动输入)。
|
||||
RuleKeyCourseCategoryDict = "course_category_dict"
|
||||
)
|
||||
|
||||
// DefaultCourseCategories 课程分类默认字典(与 defaultRuleSeed 的
|
||||
// course_category_dict、前端 DEFAULT_COURSE_CATEGORIES 一致)。
|
||||
func DefaultCourseCategories() []string {
|
||||
return []string{
|
||||
"专业技能类",
|
||||
"企业文化与制度类",
|
||||
"通用技能类",
|
||||
"安全与健康类",
|
||||
"管理领导类",
|
||||
"行业与产品知识类",
|
||||
}
|
||||
}
|
||||
|
||||
// TrainingRuleConfig 规则配置(业务规则改配置不改代码)。
|
||||
type TrainingRuleConfig struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
@@ -1032,6 +1117,7 @@ func (TrainingRuleConfig) TableName() string { return "tr_rule_configs" }
|
||||
const (
|
||||
TrainingTemplateDemandCollection = "demand_collection" // 年度教育培训收集模板.xls
|
||||
TrainingTemplateQuestionBank = "question_bank" // 部门培训课程试题(题库导入版)模板.xlsx
|
||||
TrainingTemplateCourseLibrary = "course_library" // 课程管理导入模板.xlsx
|
||||
)
|
||||
|
||||
// TrainingTemplate 租户自定义导入模板(配置中心上传,覆盖内置默认)。
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Migration: 000151_training_course_library (down)
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000151] Dropping training course library...'; END $$;
|
||||
|
||||
ALTER TABLE tr_courses
|
||||
DROP COLUMN IF EXISTS library_course_id;
|
||||
|
||||
DROP TABLE IF EXISTS tr_course_library;
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000151] Training course library dropped.'; END $$;
|
||||
@@ -0,0 +1,44 @@
|
||||
-- Migration: 000151_training_course_library
|
||||
-- 课程管理(课程资产主数据):月培训计划的「课程名称」从本表选择,
|
||||
-- 计划(tr_courses)经 library_course_id 溯源到课程管理条目。
|
||||
-- 分类 category 支持预设(通识类/知识类/实操类)与用户手动输入;
|
||||
-- 课件支持名称登记与原始文件(走 fileSvc,file_key 直取)。
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000151] Creating training course library...'; END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tr_course_library (
|
||||
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
tenant_id BIGINT NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT DEFAULT '',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '',
|
||||
type VARCHAR(16) NOT NULL DEFAULT 'required',
|
||||
mode VARCHAR(16) NOT NULL DEFAULT 'offline',
|
||||
lecturer_id VARCHAR(36) DEFAULT '',
|
||||
lecturer_external VARCHAR(64) DEFAULT '',
|
||||
hours NUMERIC(6,1) NOT NULL DEFAULT 0,
|
||||
material_name VARCHAR(255) DEFAULT '',
|
||||
file_key VARCHAR(512) DEFAULT '',
|
||||
file_name VARCHAR(255) DEFAULT '',
|
||||
file_size BIGINT NOT NULL DEFAULT 0,
|
||||
creator_id VARCHAR(36) DEFAULT '',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_tr_course_library_tenant ON tr_course_library(tenant_id) WHERE deleted_at IS NULL;
|
||||
|
||||
-- 月培训计划(tr_courses)关联课程管理条目(可空:需求确认/历史数据无关联)。
|
||||
ALTER TABLE tr_courses
|
||||
ADD COLUMN IF NOT EXISTS library_course_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN tr_courses.library_course_id IS '课程管理条目 id(月培训计划「计划名称」的来源,可空)';
|
||||
|
||||
COMMENT ON TABLE tr_course_library IS '课程管理:课程资产主数据(月培训计划从中选择课程)';
|
||||
COMMENT ON COLUMN tr_course_library.category IS '分类(通识类/知识类/实操类等,支持自定义输入)';
|
||||
COMMENT ON COLUMN tr_course_library.type IS '类型(required 必修课/elective 选修课)';
|
||||
COMMENT ON COLUMN tr_course_library.mode IS '形式(offline 线下/online 线上)';
|
||||
COMMENT ON COLUMN tr_course_library.lecturer_external IS '外部讲师姓名(导入未匹配到员工时)';
|
||||
COMMENT ON COLUMN tr_course_library.material_name IS '课件名称登记(多个用、分隔)';
|
||||
COMMENT ON COLUMN tr_course_library.file_key IS '课件原始文件 key(fileSvc 存取,可空)';
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000151] Training course library ready.'; END $$;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Migration: 000152_training_course_library_dept (down)
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000152] Dropping course library dept/participant columns...'; END $$;
|
||||
|
||||
ALTER TABLE tr_course_library
|
||||
DROP COLUMN IF EXISTS suitable_members;
|
||||
ALTER TABLE tr_course_library
|
||||
DROP COLUMN IF EXISTS owner_dept_id;
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000152] Course library dept/participant columns dropped.'; END $$;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Migration: 000152_training_course_library_dept
|
||||
-- 课程管理字段对齐《教育训练需求表》口径:
|
||||
-- owner_dept_id 所属部门(=需求表「主办单位」,存 org_depts.id,列表联查带出名称;
|
||||
-- 新增课程弹窗经组织架构部门下拉选择,批量导入按部门名匹配,未匹配留空)
|
||||
-- suitable_members 适合人员(=需求表「参加人员」,自由文本,如:财会人员)
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000152] Adding course library dept/participant columns...'; END $$;
|
||||
|
||||
ALTER TABLE tr_course_library
|
||||
ADD COLUMN IF NOT EXISTS owner_dept_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||
ALTER TABLE tr_course_library
|
||||
ADD COLUMN IF NOT EXISTS suitable_members VARCHAR(255) NOT NULL DEFAULT '';
|
||||
|
||||
COMMENT ON COLUMN tr_course_library.owner_dept_id IS '所属部门 id(org_depts,对应需求表「主办单位」;名称列表联查带出)';
|
||||
COMMENT ON COLUMN tr_course_library.suitable_members IS '适合人员(对应需求表「参加人员」,自由文本)';
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000152] Course library dept/participant columns ready.'; END $$;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Migration: 000153_training_codes (rollback)
|
||||
|
||||
DROP TABLE IF EXISTS tr_code_counters;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tr_question_banks_library_course;
|
||||
DROP INDEX IF EXISTS idx_tr_question_banks_tenant_code;
|
||||
ALTER TABLE tr_question_banks
|
||||
DROP COLUMN IF EXISTS library_course_id,
|
||||
DROP COLUMN IF EXISTS code;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tr_course_library_tenant_code;
|
||||
ALTER TABLE tr_course_library
|
||||
DROP COLUMN IF EXISTS knowledge_id,
|
||||
DROP COLUMN IF EXISTS code;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tr_courses_tenant_plan_code;
|
||||
ALTER TABLE tr_courses
|
||||
DROP COLUMN IF EXISTS source_demand_id,
|
||||
DROP COLUMN IF EXISTS plan_code;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tr_demands_tenant_code;
|
||||
ALTER TABLE tr_demands
|
||||
DROP COLUMN IF EXISTS code;
|
||||
@@ -0,0 +1,140 @@
|
||||
-- Migration: 000153_training_codes
|
||||
-- 培训域唯一编号体系(前缀+年月+流水,租户内递增):
|
||||
-- 年度需求(年培训计划) code AP-<year>-#### 按年分段
|
||||
-- 月度计划(tr_courses) plan_code MP-<YYYYMM>-#### 按月分段(取授课月份,空则取创建月)
|
||||
-- 课程管理条目 code CRS-#### 租户内流水
|
||||
-- 试题库 code QB-#### 租户内流水
|
||||
-- 附带:
|
||||
-- tr_courses.source_demand_id 计划溯源到需求(经理确认自动转月度计划)
|
||||
-- tr_question_banks.library_course_id 题库直接挂课程管理条目(试题随课程维护)
|
||||
-- tr_course_library.knowledge_id 课程管理课件同步知识库后的文档 id(AI 出题依赖)
|
||||
-- tr_code_counters 编号计数器(UPSERT 原子递增)
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000153] Adding training code columns...'; END $$;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- A. 编号列与唯一索引
|
||||
-- ---------------------------------------------------------------------------
|
||||
ALTER TABLE tr_demands
|
||||
ADD COLUMN IF NOT EXISTS code VARCHAR(32) NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tr_demands_tenant_code
|
||||
ON tr_demands(tenant_id, code) WHERE deleted_at IS NULL AND code <> '';
|
||||
|
||||
ALTER TABLE tr_courses
|
||||
ADD COLUMN IF NOT EXISTS plan_code VARCHAR(32) NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tr_courses_tenant_plan_code
|
||||
ON tr_courses(tenant_id, plan_code) WHERE deleted_at IS NULL AND plan_code <> '';
|
||||
ALTER TABLE tr_courses
|
||||
ADD COLUMN IF NOT EXISTS source_demand_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE tr_course_library
|
||||
ADD COLUMN IF NOT EXISTS code VARCHAR(32) NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tr_course_library_tenant_code
|
||||
ON tr_course_library(tenant_id, code) WHERE deleted_at IS NULL AND code <> '';
|
||||
ALTER TABLE tr_course_library
|
||||
ADD COLUMN IF NOT EXISTS knowledge_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE tr_question_banks
|
||||
ADD COLUMN IF NOT EXISTS code VARCHAR(32) NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tr_question_banks_tenant_code
|
||||
ON tr_question_banks(tenant_id, code) WHERE deleted_at IS NULL AND code <> '';
|
||||
ALTER TABLE tr_question_banks
|
||||
ADD COLUMN IF NOT EXISTS library_course_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||
CREATE INDEX IF NOT EXISTS idx_tr_question_banks_library_course
|
||||
ON tr_question_banks(tenant_id, library_course_id) WHERE deleted_at IS NULL;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- B. 编号计数器
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS tr_code_counters (
|
||||
tenant_id BIGINT NOT NULL,
|
||||
code_key VARCHAR(64) NOT NULL,
|
||||
value BIGINT NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, code_key)
|
||||
);
|
||||
COMMENT ON TABLE tr_code_counters IS '培训业务编号计数器(code_key 形如 AP:2026 / MP:202611 / CRS / QB)';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- C. 存量数据回填编号
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 年度需求:AP-<year>-####,按租户+年份内 created_at 顺序编号
|
||||
WITH numbered AS (
|
||||
SELECT id, 'AP-' || year || '-' ||
|
||||
lpad((row_number() OVER (PARTITION BY tenant_id, year ORDER BY created_at, id))::text, 4, '0') AS new_code
|
||||
FROM tr_demands
|
||||
WHERE deleted_at IS NULL AND code = ''
|
||||
)
|
||||
UPDATE tr_demands d SET code = n.new_code FROM numbered n WHERE d.id = n.id;
|
||||
|
||||
-- 月度计划(tr_courses):MP-<YYYYMM>-####,月份优先取授课时间前 7 位,否则取创建月
|
||||
WITH numbered AS (
|
||||
SELECT id,
|
||||
CASE WHEN teach_time ~ '^\d{4}-\d{2}' THEN substring(teach_time, 1, 7) ELSE to_char(created_at, 'YYYY-MM') END AS ym,
|
||||
row_number() OVER (
|
||||
PARTITION BY tenant_id,
|
||||
CASE WHEN teach_time ~ '^\d{4}-\d{2}' THEN substring(teach_time, 1, 7) ELSE to_char(created_at, 'YYYY-MM') END
|
||||
ORDER BY created_at, id
|
||||
) AS rn
|
||||
FROM tr_courses
|
||||
WHERE deleted_at IS NULL AND plan_code = ''
|
||||
)
|
||||
UPDATE tr_courses c
|
||||
SET plan_code = 'MP-' || n.ym || '-' || lpad(n.rn::text, 4, '0')
|
||||
FROM numbered n WHERE c.id = n.id;
|
||||
|
||||
-- 课程管理条目:CRS-####
|
||||
WITH numbered AS (
|
||||
SELECT id, lpad((row_number() OVER (PARTITION BY tenant_id ORDER BY created_at, id))::text, 4, '0') AS rn
|
||||
FROM tr_course_library
|
||||
WHERE deleted_at IS NULL AND code = ''
|
||||
)
|
||||
UPDATE tr_course_library l SET code = 'CRS-' || n.rn FROM numbered n WHERE l.id = n.id;
|
||||
|
||||
-- 试题库:QB-####
|
||||
WITH numbered AS (
|
||||
SELECT id, lpad((row_number() OVER (PARTITION BY tenant_id ORDER BY created_at, id))::text, 4, '0') AS rn
|
||||
FROM tr_question_banks
|
||||
WHERE deleted_at IS NULL AND code = ''
|
||||
)
|
||||
UPDATE tr_question_banks b SET code = 'QB-' || n.rn FROM numbered n WHERE b.id = n.id;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- D. 计数器种子:以存量最大流水初始化,保证新编号不与历史冲突
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO tr_code_counters (tenant_id, code_key, value)
|
||||
SELECT tenant_id, 'AP:' || year, max(split_part(code, '-', 3)::bigint)
|
||||
FROM tr_demands WHERE deleted_at IS NULL AND code <> '' GROUP BY tenant_id, year
|
||||
ON CONFLICT (tenant_id, code_key)
|
||||
DO UPDATE SET value = GREATEST(tr_code_counters.value, EXCLUDED.value), updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO tr_code_counters (tenant_id, code_key, value)
|
||||
SELECT tenant_id, 'MP:' || substring(plan_code, 4, 7), max(split_part(plan_code, '-', 3)::bigint)
|
||||
FROM tr_courses WHERE deleted_at IS NULL AND plan_code <> '' GROUP BY tenant_id, substring(plan_code, 4, 7)
|
||||
ON CONFLICT (tenant_id, code_key)
|
||||
DO UPDATE SET value = GREATEST(tr_code_counters.value, EXCLUDED.value), updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO tr_code_counters (tenant_id, code_key, value)
|
||||
SELECT tenant_id, 'CRS', max(split_part(code, '-', 2)::bigint)
|
||||
FROM tr_course_library WHERE deleted_at IS NULL AND code <> '' GROUP BY tenant_id
|
||||
ON CONFLICT (tenant_id, code_key)
|
||||
DO UPDATE SET value = GREATEST(tr_code_counters.value, EXCLUDED.value), updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO tr_code_counters (tenant_id, code_key, value)
|
||||
SELECT tenant_id, 'QB', max(split_part(code, '-', 2)::bigint)
|
||||
FROM tr_question_banks WHERE deleted_at IS NULL AND code <> '' GROUP BY tenant_id
|
||||
ON CONFLICT (tenant_id, code_key)
|
||||
DO UPDATE SET value = GREATEST(tr_code_counters.value, EXCLUDED.value), updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- E. 字段说明
|
||||
-- ---------------------------------------------------------------------------
|
||||
COMMENT ON COLUMN tr_demands.code IS '年计划编号(AP-<year>-####,创建时生成)';
|
||||
COMMENT ON COLUMN tr_courses.plan_code IS '月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时生成)';
|
||||
COMMENT ON COLUMN tr_courses.source_demand_id IS '来源需求 id(经理确认自动转月度计划时回填)';
|
||||
COMMENT ON COLUMN tr_course_library.code IS '课程编号(CRS-####,创建/导入时生成)';
|
||||
COMMENT ON COLUMN tr_course_library.knowledge_id IS '课件同步知识库「企业培训(课件)」后的文档 id(视频类留空)';
|
||||
COMMENT ON COLUMN tr_question_banks.code IS '试题库编号(QB-####,导入/创建时生成)';
|
||||
COMMENT ON COLUMN tr_question_banks.library_course_id IS '课程管理条目 id(试题随课程管理维护,可与 course_id 并存)';
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000153] Training code columns ready.'; END $$;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 000154 回滚:移除课程管理条目发布状态列。
|
||||
ALTER TABLE tr_course_library DROP COLUMN IF EXISTS publish_status;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- 000154: 课程管理条目增加发布状态(000154 需求)。
|
||||
-- 培训中心「和信课程」目录仅展示已发布课程;存量课程回填为已发布,
|
||||
-- 避免上线后目录清空,新创建/导入条目默认草稿(需人工发布)。
|
||||
ALTER TABLE tr_course_library
|
||||
ADD COLUMN IF NOT EXISTS publish_status VARCHAR(16) NOT NULL DEFAULT 'draft';
|
||||
|
||||
UPDATE tr_course_library SET publish_status = 'published' WHERE deleted_at IS NULL;
|
||||
Reference in new issue
Block a user