21 Commits
Author SHA1 Message Date
runny 0c471efb9f fix(bug):和信智汇学院上线培训 · 2026/11/27 10:00对该课程扫码签到如图所示学员信息丢失了!请核对矫正!
deploy-hxtesting / build-and-deploy (push) Successful in 1m17s
2026-11-27 18:16:01 +08:00
runny 4f77907a8a fix(SSO登录):身份判定只按工号唯一校验,邮箱降级为属性同步
deploy-hxtesting / build-and-deploy (push) Successful in 1m18s
工号相同即同一人:OIDC 登录先按 username(工号)精确命中本地账号并认回,
邮箱不同(员工改邮箱/测试 IdP 随意填写)不再分裂出 26040006-1、22030265-1
式重复账号。email 仅作工号未命中时的兜底匹配;收编后 IdP 邮箱跟随同步为
账号属性(兜底域占位邮箱不覆盖本地真实邮箱)。停用账号同样被工号命中并
由登录守卫拒绝,避免停用员工绕道拿到 -1 新号。
2026-11-27 15:20:33 +08:00
runny 043e0485e2 feat(权限优化)1.AI对话中点击快捷标签问题时,明明已经配置了默认默写为什么还会提示配置?必须点击一下保存并关闭才可以这个不对,只要配置了就可以问答不需要再让用户过来点击一次!如图一、二所示
deploy-hxtesting / build-and-deploy (push) Successful in 1m20s
2.知识库中的企业培训(课件)、企业培训(试题)、配置中心、组织架构、共享空间如图三所示可查看权限归属到超级管理员权限中!如何对
2026-11-27 14:49:06 +08:00
runny 353f60a175 fix(bug):培训中心中的和信课程点开学习页面如图所示预览查看空间高度太小,展示高度需要满屏下方留出【下载课件】按钮高度即可
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
2026-11-27 11:32:43 +08:00
runny ce24d4b9cb 月培训计划增加批量删除、批量发布功能
deploy-hxtesting / build-and-deploy (push) Successful in 1m8s
2026-11-27 01:52:44 +08:00
runny d3dcd58274 fix(培训签到)
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
2026-11-27 01:35:46 +08:00
runny d12cb873e1 fix
deploy-hxtesting / build-and-deploy (push) Successful in 1m20s
2026-11-27 01:04:15 +08:00
runny 95e74ae5d5 1.月度计划调整上传临时课件、试题后月度计划详情这里的课件名称也要跟随变更、试题!
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
2.课程管理默认模板excel下载后课程名称下拉列表不对显示了部门名称,所属部门放在列表第一列下拉选择所属部门,
3.excel时长下拉列表中显示了人员应该放到讲师字段
4.选择对应课程后默认带出课程相关信息!
2026-11-27 00:34:55 +08:00
runny aa2c89f69e fix:1.课程权限下拉列表中“全部(全员可见)”要放到列表数据第一个!
deploy-hxtesting / build-and-deploy (push) Successful in 1m17s
2.下载课程管理默认模板字段按列表字段调整!
3.课程维护完成后审核通过发布到培训中心如图四所示,打开展示区域不够大!
4,在月度计划所选课程这里重新上传课件、试题按临时上传的课件、试题作为本次培训课件、试题,如果只是改课件、试题不用审核课程可直接发布!
2026-11-26 23:54:17 +08:00
runny 0427a60bc3 fix(课程管理):课程管理模块相关调整优化
deploy-hxtesting / build-and-deploy (push) Successful in 1m20s
1.”课程编号、课程名称、所属部门、说明、课程权限、分类、类型、线上/线下、讲师、时长、课件、试题、发布状态、创建时间、创建人“可滑动部分字段从左到右顺序”课程编号、课程名称、讲师、课件、试题、课程权限、分类、类型、线上/线下、时长、发布状态、创建时间、创建人、所属部门、说明“
2.增加一个字段适合人员作为备注字段承接”年培训计划“和”月培训计划“过来的”适合人员“信息只做展示用,支持用户自定义录入,
3.”课程权限“默认当前所示部门,“全部”选项放在下拉列最前面排在部门选项上面
4.列表右侧固定字段“状态”、“操作”宽度再收窄一些
5.审核时要校验“课程名称、所属部门、课程权限、课件”必填!所属部门默认当前录入人员所属部门支持修改,课程权限也是默认当前录入人员所属部门支持修改
2026-11-26 23:07:10 +08:00
runny 2f1cda34da feat(优化):年培训计划:已确认行的删除按钮、勾选框、批量删除均仅超级管理员可见/可用;提示文案随角色变化
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
课程管理:canDeleteCourse 超管不限状态/部门(已审核/已发布行可删,确认弹窗文案区分);批量删除按钮超管可见
月培训计划:已发布行的「删除」仅超管可见(普通维护角色仍只能删未发布计划),行内确认弹窗替代原 window.confirm,失败时透出后端文案
Training.vue:canManageTabs 加入 super_admin,纯超管(未兼其他角色)也能进入这三个页面执行删除
2026-11-26 17:06:37 +08:00
runny a448598df5 fix(课程管理):CourseCatalog.vue:删除客户端权限复算(服务端 scope=catalog 是唯一权威口径);目录加载失败时空态明确提示「课程目录加载失败…请联系管理员检查服务版本与数据库迁移」,不再静默显示“暂无课程”。
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
后端权限 SQL:部门命中增加部门名回退(调用方部门名与权限部门按 org_depts 反查同名即命中,仍是同部门,无越权)。
迁移 000164 增补存量回填:旧版本时代“已审核+已有课件”但停在待发布的课程自动补发布(新流程没有发布按钮,这批课不回填会永远卡住)。
前端 onPublish:授课时间/地点校验改为“课程级字段 或 场次排期值”任一存在即放行(新增 firstUsableSession,与列表列同一取值逻辑)。
后端 PublishCourse:同样在校验前以 FirstCourseSession(新增仓储方法,排期中优先)兜底,防止前端放过、后端仍拦截。
2026-11-26 11:38:46 +08:00
runny 6defb1f2c6 fix(培训优化):1.签到码文案改「二维码有效期至 HH:mm」、代扫码按钮改「补录」;2.课程管理「适合人员」升级「课程权限」(默认所属部门,部门+人员混合选择互斥,按权限过滤目录/选课/学员视图);3.筛选增加按状态查询,核验改审核;4.审核通过即自动发布(去发布按钮),审核时课程权限必填;5.下线课程全面拦截(和信课程撤回/计划不可选/学习提示已下线,存量计划保留);6.课件管理支持多课件追加不替换(迁移000163/000164);7.AI对话问候语改「小和」;8.登录页品牌标识提升对比度
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
2026-11-26 10:20:12 +08:00
runny 9e00af1905 fix(培训签到):签到明细列口径调整——学员列显示「姓名 工号」、签到时间显示北京时间时分秒(新增 fmtBeijingTimeSec)、方式列显示中文(企微扫码/代扫码补录);代扫码补录学员下拉同步显示姓名
deploy-hxtesting / build-and-deploy (push) Successful in 1m5s
2026-11-25 16:10:23 +08:00
runny eb09f8235b fix(组织架构):1.部门列表收窄(固定280px),编码列140→64;2.修复员工档案面板溢出视口——栅格子项未收敛min-width导致右侧列与操作按钮被裁掉不可点;3.部门/员工档案列表接入共用分页组件默认每页15条
deploy-hxtesting / build-and-deploy (push) Successful in 1m4s
2026-11-25 15:33:28 +08:00
runny 0acea0eeb9 fix(月度计划):修复创建/暂存月度计划500报错——创建时不再复制课程管理条目编号
deploy-hxtesting / build-and-deploy (push) Successful in 1m9s
根因:applyLibraryCourseBinding 新建路径把课程管理条目编号(CRS-####)复制到计划行,
而 tr_courses 有 (tenant_id, code) 唯一索引,同一门课程创建第二个月度计划时必报
duplicate key(192 测试环境「暂存草稿」500 即此因)。
修复:计划编号改按租户 CRS 流水独立生成(经 library_course_id 关联主数据,
编号独立不影响带出/锁定;计数器失败留空,唯一索引豁免空编号,fail-open)。
2026-11-25 15:15:41 +08:00
runny 6f53ddc4a5 fix(优化):优化一些问题~
deploy-hxtesting / build-and-deploy (push) Successful in 1m5s
2026-11-25 15:00:08 +08:00
runny f88fce3673 fix(bug修复):1.如图四所示创建月度计划选择课程管理中的课程时下拉数据只能拉出自己部门课程
deploy-hxtesting / build-and-deploy (push) Successful in 1m12s
2.创建月度培训计划时选择课程默认展示出来的课程信息要能支持修改相关课件信息,及上传课件、试题,(修改上传后需要课长签核)
3.创建好月度计划培训后填写了授课地点但发布时一直提示如图2、3所示!
4.年度、月度培训计划列表中数据要按按计划培训时间来倒序排,创建月度计划培训时计划培训时间默认未授课培训月份!
2026-11-25 14:37:17 +08:00
runny 102d94e6c8 fix(培训页面优化):1.请检查所有企业培训相关页面带有列表展示都要进行分页,使用分页共用组件默认每页15条!
deploy-hxtesting / build-and-deploy (push) Successful in 1m8s
2.课程管理页面右侧固定太宽如图二所示收缩够用就可以,可参考培训计划页面
3.月培训计划数据默认显示计划培训和授课培训是当月数据,可筛选其他月份支持多选或全部数据
4.月培训计划只需要保留一个【创建月度计划】按钮,无法创建月度计划请核实根因!
2026-11-25 13:45:36 +08:00
runny 2483dd933a fix(扫码登录):调整签到页面
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
2026-11-25 12:34:35 +08:00
runny 21abd01593 feat(扫码签到):扫码签到方案调整~
deploy-hxtesting / build-and-deploy (push) Successful in 1m16s
2026-11-25 11:55:12 +08:00
67 changed files with 4158 additions and 998 deletions

No files matched your search

@@ -275,3 +275,16 @@
4. **轮换驱动**:后端 `GetSignCode` 读时惰性轮换(超 `rotation_sec` 窗口),讲师页每 10s 轮询;页面隐藏(`document.hidden`)暂停轮询,避免投屏不可见时的无谓轮换。 4. **轮换驱动**:后端 `GetSignCode` 读时惰性轮换(超 `rotation_sec` 窗口),讲师页每 10s 轮询;页面隐藏(`document.hidden`)暂停轮询,避免投屏不可见时的无谓轮换。
5. **验证状态**:`go build ./...` + `go vet` 全绿;前端 `vue-tsc --build` 全绿。本机 Go 测试因存量环境问题无法执行(gojieba cgo 在包 init 崩溃,干净工作树同样复现),单测需在 CI/正常环境跑:聚焦 `internal/application/service`、`internal/application/repository`、`internal/handler/training`、`internal/middleware`。 5. **验证状态**:`go build ./...` + `go vet` 全绿;前端 `vue-tsc --build` 全绿。本机 Go 测试因存量环境问题无法执行(gojieba cgo 在包 init 崩溃,干净工作树同样复现),单测需在 CI/正常环境跑:聚焦 `internal/application/service`、`internal/application/repository`、`internal/handler/training`、`internal/middleware`。
6. **联调前置(管理员)**:企微后台配 `kbt.well-trust.com`/`kb.well-trust.com` 可信域名(需确认 ICP 备案)+ 各自部署 `WW_verify_xxx.txt` + 企业可信 IP;然后测试环境走通全链路再复制到正式。 6. **联调前置(管理员)**:企微后台配 `kbt.well-trust.com`/`kb.well-trust.com` 可信域名(需确认 ICP 备案)+ 各自部署 `WW_verify_xxx.txt` + 企业可信 IP;然后测试环境走通全链路再复制到正式。
7. **redirect_uri 域名预检(联调反馈 2026-11-25)**:学员侧报"redirect_uri需使用应用可信域名"的根因与防呆 ——
- 根因 A(配置):该自建应用(IM 渠道 `corp_agent_id` 对应的那个应用)的「网页授权及JS-SDK可信域名」未配置/未生效;可信域名须与 redirect_uri 域名**精确匹配**,配在别的应用上无效;保存配置前需 `WW_verify_xxx.txt` 在 `https://<域名>/WW_verify_xxx.txt` 可访问(放 `frontend/public/` 或反代静态目录即可)。
- 根因 B(环境):二维码取讲师浏览器 origin(`SignPanel` 的 `window.location.origin`)—— 从 localhost/内网 IP 打开培训签到页生成的二维码,扫码后 redirect_uri 即为该地址,企微必拒。**必须从 kbt/kb 对外域名打开签到页再生成二维码**。
- 防呆(已实现):① 后端 `checkin-auth` 对 redirect_uri 做域名预检(`validateWecomRedirectHost`:本机/内网 IP/单标签/伪域名直接 400 并给出可行动文案;可用环境变量 `WECOM_CHECKIN_TRUSTED_DOMAINS` 配置精确白名单),失败信息展示在落地页而非手机上的企微报错;② 讲师端 `SignPanel` 检测当前页面非对外域名时,在二维码下方当场提醒重新从对外域名生成。
- 核对工具:`curl "<kbt域名>/api/v1/training/wecom/checkin-auth?token=<签到码token>"`,返回的 `authorize_url` 里 `appid`(=corpid)与 `agentid` 即本次免登使用的应用,须与后台配置可信域名的应用一致。
8. **方案调整:工号扫码签到主流程(2026-11-25 二次调整)** —— 企微可信域名配置未就绪(扫码报"redirect_uri需使用应用可信域名"且授权信息无法获取),经需求方确认改为主流程:
- **新链路**:扫码 → 落地页(课程信息+倒计时,匿名)→ 学员**手输工号** → `POST /training/wecom/checkin-by-employee`(规则引擎全量校验:签到码/轮换宽限/当天性/名单硬拒/围栏/迟到/重复/nonce 防重放)→ 工号反查档案(`org_employees.employee_no`)→ 签发会话自动登录 → 成功跳课程详情;
- **新接口**:匿名 `checkin-page-anon`(落地页数据;`employee_no` 可选,回填名单/重复标记)与 `checkin-by-employee`(签到+自动登录,nonce 必带),同挂 noAuthAPI 白名单 + 签到限流桶(600/min/IP);
- **OAuth 降级为预留通道**:`checkin-auth/checkin-session` 后端保留,前端仅在 URL 带 code+state 回跳时消费,主流程不再跳转授权页;可信域名配置就绪后可恢复为免登优先;
- **自动登录开关**:规则项 `employee_checkin_autologin`(默认 1=开;0=只签到不签发会话,前端停留成功页)——工号属半公开信息,存在知悉他人工号者冒签/冒登录的风险,已与需求方确认接受,该开关是回退手段;
- **前端**:`CheckinPage` 匿名主流程(工号输入框 + 输入工号签到按钮);已登录用户(PC 自测/已有会话)仍走登录态接口并预填工号;
- **repo 新增**:`GetMemberByEmployeeNo`(同工号多行取最早建档行,保证稳定映射);
- **独立手机端 H5(2026-11-25 三次调整)**:签到页从 `/platform` 子路由迁出为**顶层独立路由** `/m/training/checkin/:token` —— 直接渲染在 App.vue 裸 RouterView,完全脱离平台壳布局(侧栏/桌面样式),扫码免登录直达;二维码指向新路径;旧路径 `/platform/training/checkin/:token` 兼容重定向(携 query,OAuth 回跳参数不丢);移动端满屏居中样式。核实结论:路由守卫/平台布局/App.vue 均无对显式 `requiresAuth:false` 路由的登录拦截,"扫码先登录"系测试环境跑旧构建所致(旧版进页自动签到 → 401 → axios 拦截器跳登录),**验证前必须重新构建部署前后端**。
+83 -12
View File
@@ -326,6 +326,10 @@ export interface TrainingCourse {
remark?: string remark?: string
/** 课程管理条目 id(月培训计划「计划名称」从课程管理选择后关联;可空) */ /** 课程管理条目 id(月培训计划「计划名称」从课程管理选择后关联;可空) */
library_course_id?: string library_course_id?: string
/** 关联课程管理条目的发布状态(000163 联查只读;offline 时学习入口拦截) */
library_publish_status?: string
/** 关联课程管理条目是否已下线(000163;学习页提示「该课程已下线」) */
library_offline?: boolean
/** 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成) */ /** 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成) */
plan_code?: string plan_code?: string
/** 来源需求 id(经理确认自动转月度计划时回填,溯源用) */ /** 来源需求 id(经理确认自动转月度计划时回填,溯源用) */
@@ -425,6 +429,22 @@ export const deleteCourse = (id: string) =>
// ---- 课程管理(课程资产主数据;月培训计划「计划名称」数据源) ---- // ---- 课程管理(课程资产主数据;月培训计划「计划名称」数据源) ----
/** TrainingLibraryCourse 课程管理条目(000151 tr_course_library)。 */ /** TrainingLibraryCourse 课程管理条目(000151 tr_course_library)。 */
/** 课程管理课件条目(000164 多课件):一次上传/知识库挂接追加一条,不再整体替换。 */
export interface TrainingLibraryMaterial {
/** 课件条目标识(移除/预览/下载定位用) */
mid: string
/** 课件名称(上传文件名/知识库文档名) */
name: string
/** 文件字节数(知识库挂接可能为 0) */
size?: number
file_key?: string
knowledge_id?: string
/** 来源:upload 本地上传 / kb 知识库挂接 */
origin?: string
/** 上传时间(ISO 字符串) */
created_at?: string
}
export interface TrainingLibraryCourse { export interface TrainingLibraryCourse {
id: string id: string
/** 课程编号(CRS-####,创建/导入时由服务端生成,列表/详情展示) */ /** 课程编号(CRS-####,创建/导入时由服务端生成,列表/详情展示) */
@@ -437,8 +457,14 @@ export interface TrainingLibraryCourse {
owner_dept_name?: string owner_dept_name?: string
/** 说明 */ /** 说明 */
description: string description: string
/** 适合人员(对应需求表「参加人员」,自由文本,如:财会人员) */ /** 适合人员(对应需求表「参加人员」,自由文本;000163 起作课程权限展示文本) */
suitable_members?: string suitable_members?: string
/** 课程权限-可见部门 id 列表(000163,逗号分隔 org_depts.id) */
perm_dept_ids?: string
/** 课程权限-可见人员 id 列表(000163,逗号分隔 users.id) */
perm_user_ids?: string
/** 适合人员备注(000165,自由文本只做展示,不参与权限过滤;承接年/月培训计划的适合人员) */
post_scope?: string
/** 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存) */ /** 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存) */
category: string category: string
/** 类型:required 必修课 / elective 选修课 */ /** 类型:required 必修课 / elective 选修课 */
@@ -456,8 +482,10 @@ export interface TrainingLibraryCourse {
/** 课件文件(可上传,经专端点下载) */ /** 课件文件(可上传,经专端点下载) */
file_name?: string file_name?: string
file_size?: number file_size?: number
/** 课件同步知识库「企业培训(课件)」后的文档 id(AI 出题依赖) */ /** 课件同步知识库「企业培训(课件)」后的文档 id(AI 出题依赖;000164 起为最新课件条目镜像) */
knowledge_id?: string knowledge_id?: string
/** 课件列表(000164 多课件,上传/知识库挂接追加不替换) */
materials?: TrainingLibraryMaterial[]
/** 发布状态(000154):draft 草稿/published 已发布/offline 已下线 */ /** 发布状态(000154):draft 草稿/published 已发布/offline 已下线 */
publish_status?: string publish_status?: string
/** 核验状态(000157):pending 待核验/confirmed 已确认;发布前必须已确认 */ /** 核验状态(000157):pending 待核验/confirmed 已确认;发布前必须已确认 */
@@ -497,9 +525,13 @@ export const publishCourseLibraryItem = (id: string) =>
export const offlineCourseLibraryItem = (id: string) => export const offlineCourseLibraryItem = (id: string) =>
post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library/${enc(id)}/offline`) post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library/${enc(id)}/offline`)
/** 课程条目核验(000157,单个/批量共用):仅课长/经理限本部门;返回核验/跳过条数。 */ /** 课程条目核验(000163:审核即发布,单个/批量共用):仅课长/经理限本部门;
* 返回审核/跳过/自动发布条数与未传课件未发布课程名。 */
export const verifyCourseLibraryItems = (ids: string[]) => export const verifyCourseLibraryItems = (ids: string[]) =>
post<{ success: boolean; data: { verified: number; skipped: number } }>(`${base}/course-library/verify`, { ids }) post<{ success: boolean; data: { verified: number; skipped: number; auto_published: number; unpublished?: string[] } }>(
`${base}/course-library/verify`,
{ ids },
)
/** 批量导入(前端解析 Excel 后逐行提交,与需求导入同口径;返回导入条数)。 */ /** 批量导入(前端解析 Excel 后逐行提交,与需求导入同口径;返回导入条数)。 */
export const importCourseLibrary = (items: Partial<TrainingLibraryCourse>[]) => export const importCourseLibrary = (items: Partial<TrainingLibraryCourse>[]) =>
@@ -524,14 +556,15 @@ export const attachCourseLibraryMaterialFromKb = (id: string, payload: { knowled
payload, payload,
) )
/** 课件原始文件下载(在线预览/保存)。 */ /** 课件原始文件下载(在线预览/保存;000164 多课件:mid 定位条目,缺省最新一条)。 */
export const downloadCourseLibraryMaterial = (id: string) => export const downloadCourseLibraryMaterial = (id: string, mid?: string) =>
getDown(`${base}/course-library/${enc(id)}/material/file`) getDown(`${base}/course-library/${enc(id)}/material/file${mid ? `?mid=${encodeURIComponent(mid)}` : ''}`)
/** 移除课件原始文件/知识库挂接(名称登记保留;课件变更即回待核验)。 */ /** 移除课件条目(000164 多课件:mid 定位,缺省移除最新一条;课件变更即回待审核)。 */
export const removeCourseLibraryMaterial = (id: string) => export const removeCourseLibraryMaterial = (id: string, mid?: string) =>
post<{ success: boolean; data: TrainingLibraryCourse }>( post<{ success: boolean; data: TrainingLibraryCourse }>(
`${base}/course-library/${enc(id)}/material/remove`, `${base}/course-library/${enc(id)}/material/remove`,
mid ? { mid } : {},
) )
export const listSessions = (query?: ListQuery) => export const listSessions = (query?: ListQuery) =>
@@ -628,6 +661,10 @@ export interface TrainingSignRecord {
status: 'normal' | 'late' | 'abnormal' | 'duplicate' | 'outside' status: 'normal' | 'late' | 'abnormal' | 'duplicate' | 'outside'
abnormal_flags: string[] abnormal_flags: string[]
reviewed_by: string reviewed_by: string
// 后端联查回填的学员展示字段(签到明细学员列优先用它,名册反查仅兜底)
member_name?: string
employee_no?: string
dept_name?: string
} }
export interface SignSummary { export interface SignSummary {
@@ -692,6 +729,34 @@ export const wecomCheckinSession = (code: string, state: string) =>
export const wecomCheckinPage = (token: string) => export const wecomCheckinPage = (token: string) =>
post<{ success: boolean; data: WecomCheckinPageData }>(`${base}/wecom/checkin-page`, { token }) post<{ success: boolean; data: WecomCheckinPageData }>(`${base}/wecom/checkin-page`, { token })
// 工号扫码签到(2026-11-25 调整:可信域名未就绪期间的免登替代主流程)。
// page-anon:匿名落地页数据(工号非空时附带名单/重复标记);by-employee:
// 规则校验 + 工号反查档案 + 自动登录,响应内嵌 /auth/login 同构会话。
export const wecomCheckinPageAnon = (token: string, employeeNo = '') =>
post<{ success: boolean; data: WecomCheckinPageData }>(`${base}/wecom/checkin-page-anon`, {
token,
employee_no: employeeNo || undefined,
})
export interface WecomCheckinByEmployeeData extends WecomCheckinPageData {
token?: string
refresh_token?: string
user?: Record<string, any>
active_tenant?: { id: number | string; name?: string; created_at?: string; updated_at?: string } | null
memberships?: Array<{ tenant_id: number; tenant_name?: string; role: string }>
record?: TrainingSignRecord | null
}
export const wecomCheckinByEmployee = (payload: {
token: string
employee_no: string
nonce: string
lat?: number
lng?: number
client_ts?: number
}) =>
post<{ success: boolean; data: WecomCheckinByEmployeeData }>(`${base}/wecom/checkin-by-employee`, payload)
export const checkin = ( export const checkin = (
token: string, token: string,
lat = 0, lat = 0,
@@ -1191,22 +1256,28 @@ export const ROLE_DICT_RULE_KEY = 'role_dict'
export const TRAINEE_LABEL = '学员' export const TRAINEE_LABEL = '学员'
/** 系统默认职称角色(与后端 DefaultRoleDict 一致;字典缺失/损坏时兜底)。 /** 系统默认职称角色(与后端 DefaultRoleDict 一致;字典缺失/损坏时兜底)。
* 角色体系 v2:学员(隐式)/课长/经理/人事/讲师;经理继承课长全部权限并叠加审批决策。 */ * 角色体系 v2:学员(隐式)/课长/经理/人事/讲师;经理继承课长全部权限并叠加审批决策。
* v2.1 增补超级管理员:不继承任何权限组,仅承载终态数据(已确认需求/已审核课程/
* 已发布计划)的删除权,组织架构「设置角色」可分配。 */
export const DEFAULT_ROLE_DICT: TrainingRoleDef[] = [ export const DEFAULT_ROLE_DICT: TrainingRoleDef[] = [
{ key: 'hr', label: '人事', short: '人事', system: true }, { key: 'hr', label: '人事', short: '人事', system: true },
{ key: 'supervisor', label: '课长', short: '课长', system: true }, { key: 'supervisor', label: '课长', short: '课长', system: true },
{ key: 'lecturer', label: '讲师', short: '讲师', system: true }, { key: 'lecturer', label: '讲师', short: '讲师', system: true },
{ key: 'exec', label: '经理', short: '经理', system: true, inherits: ['supervisor'] }, { key: 'exec', label: '经理', short: '经理', system: true, inherits: ['supervisor'] },
{ key: 'super_admin', label: '超级管理员', short: '超管', system: true },
] ]
/** 存量角色别名:部门文员(clerk)已移除,按课长对待(与后端 LegacyRoleAlias 同构) */ /** 存量角色别名:部门文员(clerk)已移除,按课长对待(与后端 LegacyRoleAlias 同构) */
const LEGACY_ROLE_ALIAS: Record<string, string> = { clerk: 'supervisor' } const LEGACY_ROLE_ALIAS: Record<string, string> = { clerk: 'supervisor' }
/** 角色体系 v2 升级判定:经理(exec)必须继承课长,否则视为旧字典(与后端 NeedsRoleDictUpgrade 同构) */ /** 角色体系升级判定(与后端 NeedsRoleDictUpgrade 同构):
* 经理(exec)未继承课长视为 v1 旧字典;v2 口径但缺 v2.1 增补的超级管理员
* 同样需要读时升级补齐(存量租户免迁移)。 */
export function needsRoleDictUpgrade(dict: TrainingRoleDef[]): boolean { export function needsRoleDictUpgrade(dict: TrainingRoleDef[]): boolean {
const mgr = dict.find((r) => r.key === 'exec') const mgr = dict.find((r) => r.key === 'exec')
if (!mgr) return true if (!mgr) return true
return !(mgr.inherits || []).includes('supervisor') if (!(mgr.inherits || []).includes('supervisor')) return true
return !dict.some((r) => r.key === 'super_admin')
} }
/** v1 存量字典升级为 v2 视图(与后端 UpgradeRoleDictV2 同构,幂等): /** v1 存量字典升级为 v2 视图(与后端 UpgradeRoleDictV2 同构,幂等):
@@ -393,6 +393,7 @@ const getAgentNotReadyReasonKeysFor = (agent: CustomAgent, sourceTenantId?: stri
return getAgentNotReadyReasonKeys(agent.config, modelsList.value, { return getAgentNotReadyReasonKeys(agent.config, modelsList.value, {
isAgentMode, isAgentMode,
isSharedAgent, isSharedAgent,
isBuiltin: agent.is_builtin,
}); });
}; };
+1
View File
@@ -2598,6 +2598,7 @@ const collectAgentNotReadyReasons = (
const keys = getAgentNotReadyReasonKeys(agent.config, allModels.value, { const keys = getAgentNotReadyReasonKeys(agent.config, allModels.value, {
isAgentMode, isAgentMode,
isSharedAgent, isSharedAgent,
isBuiltin: agent.is_builtin,
}); });
return { return {
keys, keys,
+5 -3
View File
@@ -605,12 +605,14 @@ const moreToolItems = computed<MenuItem[]>(() => {
const items = MORE_TOOLS_ORDER const items = MORE_TOOLS_ORDER
.map(path => all.find((item: MenuItem) => item.path === path)) .map(path => all.find((item: MenuItem) => item.path === path))
.filter((item): item is MenuItem => !!item); .filter((item): item is MenuItem => !!item);
// 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底 // 末位追加「配置中心」「组织架构」(000163 权限收口:仅平台超级管理员可见,
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐) // 页面另由路由 requiresSystemAdmin 守卫兜底);「共享空间」还原至最底
// (入口定义与显隐规则仍在 menu store:仅超管可见,随能力清单显隐)
// 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由 // 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由
// /platform/training/members 由路由重定向兜底 // /platform/training/members 由路由重定向兜底
const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations'); const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations');
return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])]; const adminOnlyItems = authStore.isSystemAdmin ? [RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM] : [];
return [...items, ...adminOnlyItems, ...(orgShareItem ? [orgShareItem] : [])];
}); });
// 菜单图标统一映射:顶层项与「更多工具」子项共用 // 菜单图标统一映射:顶层项与「更多工具」子项共用
+1 -1
View File
@@ -5949,7 +5949,7 @@ export default {
} }
}, },
createChat: { createChat: {
title: 'Hi,我是 Academy,让你的知识触手可及', title: 'Hi,我是小和,让你的知识触手可及',
newSessionTitle: '新会话', newSessionTitle: '新会话',
openProject: '选择项目', openProject: '选择项目',
clearProject: '取消绑定', clearProject: '取消绑定',
+32 -12
View File
@@ -56,6 +56,17 @@ const router = createRouter({
component: () => import("../views/auth/Login.vue"), component: () => import("../views/auth/Login.vue"),
meta: { requiresAuth: false, requiresInit: false } meta: { requiresAuth: false, requiresInit: false }
}, },
{
// 学员扫码签到:独立手机端 H5 页(2026-11-25 调整)。顶层路由,直接渲染在
// App.vue 的裸 RouterView —— 完全脱离平台壳布局(侧栏/桌面样式),扫码免
// 登录直达;页面内自行完成工号签到与自动登录。显式 requiresAuth:false +
// requiresInit:false 放行路由守卫(meta 缺省 = undefined 时守卫仍按需
// 登录拦截,必须显式 false)。
path: "/m/training/checkin/:token",
name: "mobileTrainingCheckin",
component: () => import("../views/training/CheckinPage.vue"),
meta: { requiresInit: false, requiresAuth: false }
},
// Embed chat is a separate entry (embed.html + embed-main.ts), not this SPA. // Embed chat is a separate entry (embed.html + embed-main.ts), not this SPA.
{ {
path: "/register", path: "/register",
@@ -184,23 +195,24 @@ const router = createRouter({
component: () => import("../views/training/CourseDetail.vue"), component: () => import("../views/training/CourseDetail.vue"),
meta: { requiresInit: true, requiresAuth: true } meta: { requiresInit: true, requiresAuth: true }
}, },
{ {
// 学员扫码签到落地页(2026-11 企微扫码免登):企微「扫一扫」直接打开, // 旧平台内签到路径兼容重定向(2026-11-25 签到页迁移为独立手机端 H5):
// 页面内自行完成免登(OAuth 静默授权)/自动登录/倒计时/点击签到, // 已投屏/已分发的旧二维码短窗口内仍可扫;携 query 重定向,OAuth 回跳
// 故显式 requiresAuth:false + requiresInit:false 放行路由守卫 // 参数(code/state)不丢。
// (meta 缺省 = undefined 时守卫仍按需登录拦截,必须显式 false)。 path: "training/checkin/:token",
path: "training/checkin/:token", redirect: (to) => ({
name: "trainingCheckin", path: `/m/training/checkin/${to.params.token}`,
component: () => import("../views/training/CheckinPage.vue"), query: to.query
meta: { requiresInit: false, requiresAuth: false } })
}, },
{ {
// 组织架构:租户级共享组织架构(部门 + 员工档案), // 组织架构:租户级共享组织架构(部门 + 员工档案),
// 业务模块(企业培训等)按需引用,部门岗位只维护一份。 // 业务模块(企业培训等)按需引用,部门岗位只维护一份。
// 000163 权限收口:仅平台超级管理员可查看(菜单入口同步收口)。
path: "org-center", path: "org-center",
name: "orgCenter", name: "orgCenter",
component: () => import("../views/org-center/OrgCenter.vue"), component: () => import("../views/org-center/OrgCenter.vue"),
meta: { requiresInit: true, requiresAuth: true } meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }
}, },
{ {
path: "agents", path: "agents",
@@ -247,7 +259,8 @@ const router = createRouter({
path: "organizations", path: "organizations",
name: "organizationList", name: "organizationList",
component: () => import("../views/organization/OrganizationList.vue"), component: () => import("../views/organization/OrganizationList.vue"),
meta: { requiresInit: true, requiresAuth: true, requiredCapability: 'organizations' } // 000163 权限收口:共享空间仅平台超级管理员可查看(菜单入口同步收口)。
meta: { requiresInit: true, requiresAuth: true, requiredCapability: 'organizations', requiresSystemAdmin: true }
}, },
// Compatibility redirects for /platform/system/* URLs. System // Compatibility redirects for /platform/system/* URLs. System
// administration surfaces live as dedicated sections inside the // administration surfaces live as dedicated sections inside the
@@ -457,6 +470,13 @@ router.beforeEach(async (to, from, next) => {
} }
} }
// 培训路由按 tab 共用(training/:tab),「配置中心」(rules) 页签单独收口:
// 仅平台超级管理员可查看,其余用户弹回培训工作台(000163)。
if (to.name === 'trainingTab' && String(to.params.tab) === 'rules' && !authStore.isSystemAdmin) {
next('/platform/training/dashboard')
return
}
next() next()
}) })
+3 -4
View File
@@ -76,9 +76,8 @@ export const useMenuStore = defineStore('menuStore', () => {
const liteHiddenPaths = new Set(['logout', 'organizations']) const liteHiddenPaths = new Set(['logout', 'organizations'])
// 共享空间 (organizations) 仅对当前空间的 admin / owner 暴露入口。 // 共享空间 (organizations) 仅对平台超级管理员暴露入口(000163 权限收口:
// viewer / contributor 即便在共享空间里拥有资源,也无需自行管理共享关系, // 原为空间 admin/owner 可见)。后端 RBAC 才是权限的最终来源(见 middleware/rbac.go)。
// 入口在侧栏只会徒增噪音;后端 RBAC 才是权限的最终来源(见 middleware/rbac.go)。
const visibleMenuArr = computed(() => { const visibleMenuArr = computed(() => {
const authStore = useAuthStore() const authStore = useAuthStore()
const deploymentCapabilities = useDeploymentCapabilitiesStore() const deploymentCapabilities = useDeploymentCapabilitiesStore()
@@ -86,7 +85,7 @@ export const useMenuStore = defineStore('menuStore', () => {
if (authStore.isLiteMode && liteHiddenPaths.has(item.path)) { if (authStore.isLiteMode && liteHiddenPaths.has(item.path)) {
return false return false
} }
if (item.path === 'organizations' && !authStore.hasRole('admin')) { if (item.path === 'organizations' && !authStore.isSystemAdmin) {
return false return false
} }
if (!deploymentCapabilities.isSupported(item.requiredCapability)) { if (!deploymentCapabilities.isSupported(item.requiredCapability)) {
+48 -9
View File
@@ -163,11 +163,13 @@ export const TRAINING_MOCK = {
}, },
} }
// 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致) // 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致);
// 000163 课程权限:perm_dept_ids/perm_user_ids 为空时沿用 suitable_members 口径;
// 000164 多课件:materials 逐条追加
const COURSE_LIBRARY_MOCK = [ 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: '入职通识手册.pptx', file_size: 839680, knowledge_id: 'kb-lib1', question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) }, { id: 'lib-1', code: 'CRS-0001', name: '新员工入职通识培训', owner_dept_id: 'dept-b', owner_dept_name: '技术部', description: '公司制度、企业文化与办公系统入门', suitable_members: '全部', perm_dept_ids: '', perm_user_ids: '', materials: [{ mid: 'm-11', name: '入职通识手册.pptx', size: 839680, file_key: 'fk-11', knowledge_id: 'kb-lib1', origin: 'upload', created_at: '' }, { mid: 'm-12', name: '员工手册速查.pdf', size: 402112, file_key: 'fk-12', knowledge_id: '', origin: 'upload', created_at: '' }], category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '员工手册速查.pdf', file_size: 402112, knowledge_id: 'kb-lib1', question_bank_count: 1, verify_status: 'confirmed', publish_status: 'published', 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: '安全操作规程.docx', file_size: 512000, question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) }, { id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压车间', perm_dept_ids: 'dept-a', perm_user_ids: '', materials: [{ mid: 'm-21', name: '安全操作规程.docx', size: 512000, file_key: 'fk-21', knowledge_id: '', origin: 'upload', created_at: '' }], category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '安全操作规程.docx', file_size: 512000, question_bank_count: 1, verify_status: 'pending', publish_status: 'draft', 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, question_bank_count: 0, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) }, { id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', perm_dept_ids: '', perm_user_ids: '', materials: [], category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, question_bank_count: 0, verify_status: 'pending', publish_status: 'draft', lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) },
] ]
// 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####) // 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####)
@@ -314,12 +316,17 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
return ok({ id: `q-new-${Date.now()}`, seq_no: 0 }) return ok({ id: `q-new-${Date.now()}`, seq_no: 0 })
} }
// 课件管理抽屉:上传/知识库挂接/移除回显对应课程条目并模拟文件字段变更 // 课件管理抽屉:上传/知识库挂接/移除回显对应课程条目并模拟文件字段变更
// (000164 多课件:上传/挂接追加条目,移除按 mid 或最新一条)
if (url.includes('/course-library/') && url.includes('/material/remove')) { if (url.includes('/course-library/') && url.includes('/material/remove')) {
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`)) const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
if (course) { if (course) {
course.file_name = '' const list = course.materials || []
course.file_size = 0 list.pop()
course.knowledge_id = '' course.materials = list
const latest = list[list.length - 1]
course.file_name = latest?.name || ''
course.file_size = latest?.size || 0
course.knowledge_id = latest?.knowledge_id || ''
course.verify_status = 'pending' course.verify_status = 'pending'
} }
return ok(course || { id: `c-new-${Date.now()}` }) return ok(course || { id: `c-new-${Date.now()}` })
@@ -327,8 +334,10 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
if (url.includes('/course-library/') && url.includes('/material')) { if (url.includes('/course-library/') && url.includes('/material')) {
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`)) const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
if (course) { if (course) {
course.file_name = '预览课件.pdf' const entry = { mid: `m-${Date.now()}`, name: '预览课件.pdf', size: 1024 * 820, file_key: 'fk-new', knowledge_id: '', origin: 'upload', created_at: new Date().toISOString() }
course.file_size = 1024 * 820 course.materials = [...(course.materials || []), entry]
course.file_name = entry.name
course.file_size = entry.size
course.verify_status = 'pending' course.verify_status = 'pending'
} }
return ok(course || { id: `c-new-${Date.now()}` }) return ok(course || { id: `c-new-${Date.now()}` })
@@ -336,5 +345,35 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
if (url.includes('/course-library/') && url.includes('/question-banks/import')) { 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: `b-new-${Date.now()}`, code: `QB-${String(QUESTION_BANKS_MOCK.length + 1).padStart(4, '0')}`, name: '新导入题库', question_count: 5 })
} }
// 审核(000163:审核即发布):pending → confirmed + published(有课件时)
// (预览 harness 不解析请求体,对全部 pending 条目生效)
if (url.includes('/course-library/verify')) {
let verified = 0
let autoPublished = 0
const unpublished: string[] = []
for (const course of COURSE_LIBRARY_MOCK) {
if (course.verify_status !== 'pending') continue
course.verify_status = 'confirmed'
verified += 1
if (course.file_name || course.knowledge_id) {
course.publish_status = 'published'
autoPublished += 1
} else {
unpublished.push(course.name)
}
}
return ok({ verified, skipped: 0, auto_published: autoPublished, unpublished })
}
// 下线(000163:下线后从和信课程撤回,计划存量行保留)
if (url.includes('/course-library/') && url.includes('/offline')) {
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/offline`))
if (course) course.publish_status = 'offline'
return ok(course || { id: `c-new-${Date.now()}` })
}
if (url.includes('/course-library/') && url.includes('/publish')) {
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/publish`))
if (course) course.publish_status = 'published'
return ok(course || { id: `c-new-${Date.now()}` })
}
return ok({ id: `c-new-${Date.now()}` }) return ok({ id: `c-new-${Date.now()}` })
} }
+62 -6
View File
@@ -9,10 +9,29 @@ import {
resolveAgentNotReadyHighlight, resolveAgentNotReadyHighlight,
} from './agent-readiness.ts' } from './agent-readiness.ts'
test('does not treat an unrelated built-in chat model as agent configuration', () => { test('an empty model_id falls back to the workspace default chat model', () => {
// Built-in agents are seeded without model_id; the run resolves the
// workspace default, so they are ready as long as one exists.
assert.equal(agentHasConfiguredChatModel( assert.equal(agentHasConfiguredChatModel(
{}, {},
[{ id: 'builtin-chat', type: 'KnowledgeQA' }], [{ id: 'builtin-chat', type: 'KnowledgeQA' }],
), true)
})
test('an empty model_id is not ready when the workspace has no KnowledgeQA model', () => {
assert.equal(agentHasConfiguredChatModel(
{},
[{ id: 'embed-1', type: 'Embedding' }],
), false)
assert.equal(agentHasConfiguredChatModel({}, []), false)
})
test('an empty model_id stays unready for shared agents', () => {
// The model belongs to the source tenant; existence is validated backend-side.
assert.equal(agentHasConfiguredChatModel(
{},
[{ id: 'builtin-chat', type: 'KnowledgeQA' }],
true,
), false) ), false)
}) })
@@ -110,25 +129,62 @@ test('resolveAgentNotReadyHighlight returns the first missing item', () => {
assert.equal(resolveAgentNotReadyHighlight([]), undefined) assert.equal(resolveAgentNotReadyHighlight([]), undefined)
}) })
test('getAgentNotReadyReasonKeys flags missing chat model', () => { test('getAgentNotReadyReasonKeys flags a missing chat model only without a workspace default', () => {
// No KnowledgeQA model in the workspace: nothing to fall back to.
assert.deepEqual(getAgentNotReadyReasonKeys(
{},
[],
{ isAgentMode: false, isSharedAgent: false },
), ['summary_model'])
// Workspace default exists: the empty model_id resolves at run time.
assert.deepEqual(getAgentNotReadyReasonKeys( assert.deepEqual(getAgentNotReadyReasonKeys(
{}, {},
[{ id: 'chat-1', type: 'KnowledgeQA' }], [{ id: 'chat-1', type: 'KnowledgeQA' }],
{ isAgentMode: false, isSharedAgent: false }, { isAgentMode: false, isSharedAgent: false },
), [])
// Shared agents must declare an explicit model; cannot validate locally.
assert.deepEqual(getAgentNotReadyReasonKeys(
{},
[{ id: 'chat-1', type: 'KnowledgeQA' }],
{ isAgentMode: false, isSharedAgent: true },
), ['summary_model']) ), ['summary_model'])
}) })
test('getAgentNotReadyReasonKeys requires rerank only in agent mode with KB search', () => { test('getAgentNotReadyReasonKeys requires rerank only in agent mode with KB search', () => {
assert.deepEqual(getAgentNotReadyReasonKeys( assert.deepEqual(getAgentNotReadyReasonKeys(
{ kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] },
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
{ isAgentMode: true, isSharedAgent: false }, { isAgentMode: true, isSharedAgent: false },
), ['summary_model', 'rerank_model']) ), ['rerank_model'])
assert.deepEqual(getAgentNotReadyReasonKeys( assert.deepEqual(getAgentNotReadyReasonKeys(
{ kb_selection_mode: 'all', allowed_tools: ['knowledge_search'] }, { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['knowledge_search'] },
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
{ isAgentMode: true, isSharedAgent: false }, { isAgentMode: true, isSharedAgent: false },
), ['summary_model', 'rerank_model']) ), ['rerank_model'])
})
test('built-in agents fall back to the workspace rerank without a reason', () => {
// Mirrors session_agent_qa.go: empty rerank on a builtin resolves from the
// workspace (or searches without reranking) instead of blocking the run.
assert.deepEqual(getAgentNotReadyReasonKeys(
{ model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] },
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
{ isAgentMode: true, isSharedAgent: false, isBuiltin: true },
), [])
// Even with no rerank model at all: builtin searches without reranking.
assert.deepEqual(getAgentNotReadyReasonKeys(
{ model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] },
[{ id: 'chat-1', type: 'KnowledgeQA' }],
{ isAgentMode: true, isSharedAgent: false, isBuiltin: true },
), [])
})
test('custom agents without a rerank model stay flagged', () => {
assert.deepEqual(getAgentNotReadyReasonKeys(
{ model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] },
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
{ isAgentMode: true, isSharedAgent: false, isBuiltin: false },
), ['rerank_model'])
}) })
test('getAgentNotReadyReasonKeys does not treat current shared context as shared without sourceTenantId', () => { test('getAgentNotReadyReasonKeys does not treat current shared context as shared without sourceTenantId', () => {
+40 -13
View File
@@ -1,28 +1,47 @@
import type { CustomAgentConfig } from '@/api/agent' import type { CustomAgentConfig } from '@/api/agent'
import type { ModelConfig } from '@/api/model' import type { ModelConfig } from '@/api/model'
import { allowedToolsInclude } from './legacy-tool-names' import { allowedToolsInclude } from './legacy-tool-names'
import { selectInitialModelId } from './modelDefaults'
export type AgentNotReadyReasonKey = 'summary_model' | 'rerank_model' | 'allowed_tools' export type AgentNotReadyReasonKey = 'summary_model' | 'rerank_model' | 'allowed_tools'
/** /**
* An agent is chat-ready only when it explicitly references a usable chat * An agent is chat-ready when it references a usable chat model, or when it
* model. Merely having some built-in/default model in the tenant must not hide * may fall back to the workspace default: an empty model_id is resolved at run
* incomplete agent configuration. * time from the agent's knowledge base or the workspace's default KnowledgeQA
* model (backend UsesWorkspaceModelFallback + selectChatModelID), so a local
* agent without an explicit model is ready as long as the workspace has a
* usable default. Only a model_id that points at a missing/non-KnowledgeQA
* model counts as incomplete configuration.
* *
* For shared agents the model belongs to the source tenant, so the caller can * For shared agents the model belongs to the source tenant, so the caller can
* require a non-empty ID but must leave existence validation to the backend. * require a non-empty ID but must leave existence validation to the backend.
*/ */
export function agentHasConfiguredChatModel( export function agentHasConfiguredChatModel(
config: Pick<CustomAgentConfig, 'model_id'> | undefined, config: Pick<CustomAgentConfig, 'model_id'> | undefined,
models: Pick<ModelConfig, 'id' | 'type'>[], models: Pick<ModelConfig, 'id' | 'type' | 'status'>[],
sourceModelIsRemote = false, sourceModelIsRemote = false,
): boolean { ): boolean {
const modelID = config?.model_id?.trim() const modelID = config?.model_id?.trim()
if (!modelID) return false if (!modelID) {
if (sourceModelIsRemote) return false
return hasWorkspaceDefaultChatModel(models)
}
if (sourceModelIsRemote) return true if (sourceModelIsRemote) return true
return models.some(model => model.type === 'KnowledgeQA' && model.id === modelID) return models.some(model => model.type === 'KnowledgeQA' && model.id === modelID)
} }
/**
* Workspace default chat model: the declared KnowledgeQA default, else the
* first active KnowledgeQA model — same rule as the backend's
* PickDefaultModelID and the agent editor's auto pre-fill.
*/
export function hasWorkspaceDefaultChatModel(
models: Pick<ModelConfig, 'id' | 'type' | 'status'>[],
): boolean {
return selectInitialModelId(models, 'KnowledgeQA') != null
}
/** /**
* Keep this aligned with backend agentRequiresRerankModel. * Keep this aligned with backend agentRequiresRerankModel.
* *
@@ -50,8 +69,8 @@ export function getAgentNotReadyReasonKeys(
CustomAgentConfig, CustomAgentConfig,
'model_id' | 'rerank_model_id' | 'kb_selection_mode' | 'allowed_tools' | 'agent_mode' 'model_id' | 'rerank_model_id' | 'kb_selection_mode' | 'allowed_tools' | 'agent_mode'
> | undefined, > | undefined,
models: Pick<ModelConfig, 'id' | 'type'>[], models: Pick<ModelConfig, 'id' | 'type' | 'status'>[],
options: { isAgentMode: boolean; isSharedAgent: boolean }, options: { isAgentMode: boolean; isSharedAgent: boolean; isBuiltin?: boolean },
): AgentNotReadyReasonKey[] { ): AgentNotReadyReasonKey[] {
const reasons: AgentNotReadyReasonKey[] = [] const reasons: AgentNotReadyReasonKey[] = []
@@ -61,12 +80,20 @@ export function getAgentNotReadyReasonKeys(
if (options.isAgentMode && agentRequiresRerankModel(config)) { if (options.isAgentMode && agentRequiresRerankModel(config)) {
const rerankModelID = config?.rerank_model_id?.trim() const rerankModelID = config?.rerank_model_id?.trim()
const rerankExists = !!rerankModelID && ( if (!rerankModelID) {
options.isSharedAgent // Built-in agents are seeded without a rerank model; the run falls back
|| models.some(model => model.type === 'Rerank' && model.id === rerankModelID) // to the workspace rerank (or searches without reranking) instead of
) // blocking, mirroring session_agent_qa.go's UsesWorkspaceModelFallback
if (!rerankExists) { // branch. Custom agents must declare their own rerank model.
reasons.push('rerank_model') if (!options.isBuiltin || options.isSharedAgent) {
reasons.push('rerank_model')
}
} else {
const rerankExists = options.isSharedAgent
|| models.some(model => model.type === 'Rerank' && model.id === rerankModelID)
if (!rerankExists) {
reasons.push('rerank_model')
}
} }
} }
+19
View File
@@ -17,6 +17,17 @@ const BEIJING_CLOCK = new Intl.DateTimeFormat('zh-CN', {
hour12: false, hour12: false,
}) })
const BEIJING_DATETIME_SEC = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
/** fmtBeijingTime 任意时间戳 → 北京时间「YYYY/MM/DD HH:mm」(无秒);空/非法输入返回空串。 */ /** fmtBeijingTime 任意时间戳 → 北京时间「YYYY/MM/DD HH:mm」(无秒);空/非法输入返回空串。 */
export function fmtBeijingTime(raw: string | number | Date | null | undefined): string { export function fmtBeijingTime(raw: string | number | Date | null | undefined): string {
if (raw === null || raw === undefined || raw === '') return '' if (raw === null || raw === undefined || raw === '') return ''
@@ -32,3 +43,11 @@ export function fmtBeijingClock(raw: string | number | Date | null | undefined):
if (Number.isNaN(date.getTime())) return '' if (Number.isNaN(date.getTime())) return ''
return BEIJING_CLOCK.format(date) return BEIJING_CLOCK.format(date)
} }
/** fmtBeijingTimeSec 北京时间「YYYY/MM/DD HH:mm:ss」(带秒;签到明细等需秒级精度的场景)。 */
export function fmtBeijingTimeSec(raw: string | number | Date | null | undefined): string {
if (raw === null || raw === undefined || raw === '') return ''
const date = raw instanceof Date ? raw : new Date(raw)
if (Number.isNaN(date.getTime())) return ''
return BEIJING_DATETIME_SEC.format(date)
}
+18
View File
@@ -1246,6 +1246,24 @@ onMounted(async () => {
width: 120px; width: 120px;
height: auto; height: auto;
} }
// 品牌标识增强(测试反馈 2026-11-26):登录页为深绿渐变背景,共用 Logo 的
// 绿色渐变文字对比度不足 —— 此处覆写为白色高亮文字(保留流光动效)并放大字号,
// 光点同步提亮;侧边栏(白底)不受影响,仍用共用样式。
.aido-logo__text {
font-size: 23px;
letter-spacing: 2.5px;
background-image:
linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.95) 50%, rgba(255, 255, 255, 0) 58%),
linear-gradient(180deg, #ffffff 0%, #e8fff2 100%);
-webkit-text-fill-color: transparent;
filter: drop-shadow(0 1px 8px rgba(0, 64, 32, 0.6));
}
.aido-logo__dot {
background: radial-gradient(circle at 35% 35%, #ffffff, #7df7c3 60%);
box-shadow: 0 0 7px 2px rgba(255, 255, 255, 0.65);
}
} }
.header-links { .header-links {
+118 -42
View File
@@ -21,14 +21,19 @@
<span class="panel-box__title">部门</span> <span class="panel-box__title">部门</span>
<t-button theme="primary" @click="openCreateDept">新增部门</t-button> <t-button theme="primary" @click="openCreateDept">新增部门</t-button>
</div> </div>
<t-table :data="depts" :columns="deptColumns" row-key="id" size="small"> <!-- 表格滚动区:面板满屏,表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<template #op="{ row }"> <div class="table-scroll">
<div class="op-group"> <t-table :data="pagedDepts" :columns="deptColumns" row-key="id" size="small" height="100%">
<t-button variant="text" theme="primary" size="small" @click="onEditDept(row)">修改</t-button> <template #op="{ row }">
<t-button variant="text" theme="danger" size="small" @click="onDeleteDept(row)">删除</t-button> <div class="op-group">
</div> <t-button variant="text" theme="primary" size="small" @click="onEditDept(row)">修改</t-button>
</template> <t-button variant="text" theme="danger" size="small" @click="onDeleteDept(row)">删除</t-button>
</t-table> </div>
</template>
</t-table>
</div>
<!-- 共用分页(000164):默认每页 15 条 -->
<TrainingPagination v-model:current="deptPage" v-model:page-size="deptPageSize" :total="deptTotal" />
</div> </div>
<div class="panel-box org-layout__employees"> <div class="panel-box org-layout__employees">
@@ -64,32 +69,37 @@
<t-button theme="primary" @click="importVisible = true">批量导入</t-button> <t-button theme="primary" @click="importVisible = true">批量导入</t-button>
</div> </div>
</div> </div>
<t-table :data="employees" :columns="employeeColumns" row-key="id" size="small" :loading="loading"> <!-- 表格滚动区:面板满屏,表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<template #user_name="{ row }"> <div class="table-scroll">
<t-tooltip :content="employeeName(row)" :disabled="!employeeName(row)"> <t-table :data="pagedEmployees" :columns="employeeColumns" row-key="id" size="small" height="100%" :loading="loading">
<span class="employee-name">{{ employeeName(row) || '-' }}</span> <template #user_name="{ row }">
</t-tooltip> <t-tooltip :content="employeeName(row)" :disabled="!employeeName(row)">
</template> <span class="employee-name">{{ employeeName(row) || '-' }}</span>
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template> </t-tooltip>
<template #wecom_userid="{ row }"> </template>
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span> <template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
</template> <template #wecom_userid="{ row }">
<template #roles="{ row }"> <span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag> </template>
</template> <template #roles="{ row }">
<template #status="{ row }"> <t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
<t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag> </template>
<t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag> <template #status="{ row }">
<t-tag v-else theme="default" variant="light" size="small">{{ row.status || '-' }}</t-tag> <t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag>
</template> <t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag>
<template #op="{ row }"> <t-tag v-else theme="default" variant="light" size="small">{{ row.status || '-' }}</t-tag>
<div class="op-group"> </template>
<t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button> <template #op="{ row }">
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button> <div class="op-group">
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button> <t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button>
</div> <t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
</template> <t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
</t-table> </div>
</template>
</t-table>
</div>
<!-- 共用分页(000164):默认每页 15 条 -->
<TrainingPagination v-model:current="employeePage" v-model:page-size="employeePageSize" :total="employeeTotal" />
</div> </div>
</div> </div>
</div> </div>
@@ -321,6 +331,8 @@ import {
} from '@/api/training' } from '@/api/training'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import ResourceIcon from '@/components/icons/ResourceIcon.vue' import ResourceIcon from '@/components/icons/ResourceIcon.vue'
import TrainingPagination from '../training/components/TrainingPagination.vue'
import { useTrainingPager } from '../training/components/useTrainingPager'
const authStore = useAuthStore() const authStore = useAuthStore()
const loading = ref(false) const loading = ref(false)
@@ -355,9 +367,9 @@ const roleDict = ref<TrainingRoleDef[]>([])
// 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护) // 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护)
const rawRoles = ref<string[]>([]) const rawRoles = ref<string[]>([])
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value)) const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
const canManage = computed( // 000163 权限收口:组织架构页仅平台超级管理员可查看/维护
() => authStore.hasRole('admin') || myRoles.value.some((r) => r === 'hr' || r === 'exec'), // (路由 requiresSystemAdmin 守卫为主,此处为页面内兜底)。
) const canManage = computed(() => authStore.isSystemAdmin)
const rolesVisible = ref(false) const rolesVisible = ref(false)
const activeEmployee = ref<OrgEmployee | null>(null) const activeEmployee = ref<OrgEmployee | null>(null)
@@ -518,9 +530,10 @@ const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
const deptColumns = [ const deptColumns = [
{ colKey: 'name', title: '部门名称' }, { colKey: 'name', title: '部门名称' },
{ colKey: 'code', title: '编码', width: 140 }, // 000164:编码列收窄(0001 等短编码无需过宽列,原 140px 留白明显)
{ colKey: 'code', title: '编码', width: 64 },
// 窄屏下列宽超出面板时操作列随滚动固定在右侧,保证可见可点 // 窄屏下列宽超出面板时操作列随滚动固定在右侧,保证可见可点
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' }, { colKey: 'op', title: '操作', width: 116, fixed: 'right' },
] ]
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新) // 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
@@ -597,6 +610,28 @@ watch(keyword, () => {
searchTimer = setTimeout(() => loadEmployees(), 300) searchTimer = setTimeout(() => loadEmployees(), 300)
}) })
// 共用分页(000164):部门/员工档案列表默认每页 15 条;
// 查找或增删改刷新列表后回到第 1 页
const {
page: deptPage,
pageSize: deptPageSize,
total: deptTotal,
paged: pagedDepts,
reset: resetDeptPage,
} = useTrainingPager(depts)
const {
page: employeePage,
pageSize: employeePageSize,
total: employeeTotal,
paged: pagedEmployees,
reset: resetEmployeePage,
} = useTrainingPager(employees)
watch([depts, employees], () => {
resetDeptPage()
resetEmployeePage()
})
const loadAll = async () => { const loadAll = async () => {
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。 // 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
const [d, u] = await Promise.all([ const [d, u] = await Promise.all([
@@ -824,20 +859,61 @@ onMounted(() => {
padding: var(--app-space-3) 0 var(--app-space-6); padding: var(--app-space-3) 0 var(--app-space-6);
} }
// 3/7 分栏:部门列占 3,员工档案列占 7;窄屏退化为单列 // 分栏:部门列收窄为固定宽度(000164,原 3fr 过宽且编码列留白明显),
// 员工档案占剩余全部宽度;窄屏退化为单列。
// 满屏布局(000164 布局诉求):栅格占满页身剩余高度,两面板各自内部滚动 ——
// 面板头(标题/操作/查找)/表头/分页固定,仅表格数据区滚动;窄屏单列回退整页滚动
.org-layout { .org-layout {
display: grid; display: grid;
grid-template-columns: 3fr 7fr; grid-template-columns: 280px minmax(0, 1fr);
// 满屏关键:行高锁定为容器高(grid 行默认 auto 会被内容撑开,面板 height:100%
// 的百分比链随之失效,表头/分页固定就不生效了)
grid-template-rows: minmax(0, 1fr);
gap: 12px; gap: 12px;
align-items: start; height: 100%;
min-height: 0;
@media (max-width: 900px) { @media (max-width: 900px) {
grid-template-columns: 1fr; grid-template-columns: 1fr;
grid-template-rows: none;
height: auto;
}
// 000164 栅格子项收敛:员工档案表格/工具行较宽,缺省 min-width 会把
// 栅格轨道撑出视口,右侧列与操作按钮被裁掉不可见不可点;
// 收敛后表格在面板内横向滚动,操作列 fixed:right 始终可见
> .panel-box {
min-width: 0;
} }
} }
.panel-box { .panel-box {
.training-panel-box(); .training-panel-box();
.org-layout & {
display: flex;
flex-direction: column;
height: 100%;
@media (max-width: 900px) {
height: auto;
}
}
// 面板头固定,表格滚动区撑满剩余高度(表格 height=100% 启用 TDesign 固定表头;
// .t-table 根也要撑满 100%,否则百分比退化为内容高、表头固定不生效)
.org-layout & > .table-scroll {
flex: 1;
min-height: 0;
> .t-table {
height: 100%;
}
}
.org-layout & > .training-pagination {
flex-shrink: 0;
}
} }
.form-hint { .form-hint {
+159 -97
View File
@@ -1,11 +1,14 @@
<template> <template>
<!-- 学员扫码签到落地页(2026-11 企微扫码免登需求): <!-- 学员扫码签到落地页(2026-11-25 调整:工号主流程):
企微「扫一扫」→ 静默免登(自动登录)→ 课程信息 + 签到倒计时 → 点击签到 企微「扫一扫」→ 落地页(课程信息 + 签到倒计时)→ 手输工号 → 点击签到
→ 成功后自动进入该课程详情页。非企微环境提示改用企微扫码。 --> → 规则校验(当天/名单/围栏/迟到/重复/防重放)+ 工号反查档案 + 自动登录
→ 成功后自动进入该课程详情页。
企微 OAuth 静默免登链路保留为预留通道(可信域名配置就绪后恢复,见
checkin-session 回跳分支),当前默认不走 OAuth。 -->
<div class="checkin-page"> <div class="checkin-page">
<div class="checkin-card"> <div class="checkin-card">
<div class="checkin-card__icon" :class="`is-${iconState}`"> <div class="checkin-card__icon" :class="`is-${iconState}`">
<!-- 免登中/取位中 --> <!-- 加载中/取位中 -->
<svg v-if="iconState === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"> <svg v-if="iconState === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3.2" /> <circle cx="12" cy="12" r="3.2" />
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" /> <path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
@@ -30,7 +33,7 @@
{{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }} {{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }}
</t-tag> </t-tag>
<!-- 落地页主体:课程信息 + 身份确认行 + 倒计时 + 签到按钮 --> <!-- 落地页主体:课程信息 + 工号输入/确认行 + 倒计时 + 签到按钮 -->
<template v-if="state === 'ready' && page"> <template v-if="state === 'ready' && page">
<div class="course-box"> <div class="course-box">
<div class="course-box__name">{{ page.course?.course_name || '培训课程' }}</div> <div class="course-box__name">{{ page.course?.course_name || '培训课程' }}</div>
@@ -40,6 +43,18 @@
<div class="course-box__row" v-if="memberLabel">签到人:{{ memberLabel }}</div> <div class="course-box__row" v-if="memberLabel">签到人:{{ memberLabel }}</div>
</div> </div>
<!-- 工号输入:匿名主流程(免登 OAuth 未启用,学员手输工号签到) -->
<div v-if="needEmployeeNo" class="emp-no-box">
<t-input
v-model="employeeNoInput"
placeholder="请输入您的工号"
size="large"
clearable
@enter="sign"
/>
<div class="emp-no-box__hint">签到将以工号核验「参加人员」名单,请确认输入本人工号</div>
</div>
<!-- 签到倒计时:当前签到码剩余有效期,归零须重新扫码(需求补充 2) --> <!-- 签到倒计时:当前签到码剩余有效期,归零须重新扫码(需求补充 2) -->
<div class="countdown" :class="{ 'is-danger': remainSec <= 60 }"> <div class="countdown" :class="{ 'is-danger': remainSec <= 60 }">
<template v-if="remainSec > 0"> <template v-if="remainSec > 0">
@@ -74,36 +89,36 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import { userInfoFromApi, } from '@/api/auth' import { userInfoFromApi } from '@/api/auth'
import { import {
checkin, checkin,
getCheckinAuthUrl,
unwrap, unwrap,
wecomCheckinByEmployee,
wecomCheckinPage, wecomCheckinPage,
wecomCheckinPageAnon,
wecomCheckinSession, wecomCheckinSession,
type TrainingSignRecord, type TrainingSignRecord,
type WecomCheckinByEmployeeData,
type WecomCheckinPageData, type WecomCheckinPageData,
type WecomCheckinSessionData,
} from '@/api/training' } from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
import { apiErrorMessage } from '@/utils/request'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const authStore = useAuthStore() const authStore = useAuthStore()
type CheckinState = 'boot' | 'authing' | 'ready' | 'submitting' | 'success' | 'error' | 'blocked' type CheckinState = 'boot' | 'ready' | 'submitting' | 'success' | 'error' | 'blocked'
const state = ref<CheckinState>('boot') const state = ref<CheckinState>('boot')
const page = ref<WecomCheckinPageData | null>(null) const page = ref<WecomCheckinPageData | null>(null)
const record = ref<TrainingSignRecord | null>(null) const record = ref<TrainingSignRecord | null>(null)
const errorMsg = ref('') const errorMsg = ref('')
// 定位坐标:拒绝授权/不可用时以 0,0 提交,由后端 sign_policy(强制定位)决定是否放行 // 定位坐标:拒绝授权/不可用时以 0,0 提交,由后端 sign_policy(强制定位)决定是否放行
const geo = ref({ lat: 0, lng: 0 }) const geo = ref({ lat: 0, lng: 0 })
// 工号输入(匿名主流程);已登录(PC 自测/已有会话)由档案预填为确认行
const employeeNoInput = ref('')
const routeToken = computed(() => String(route.params.token || '')) const routeToken = computed(() => String(route.params.token || ''))
// 企微内置浏览器 UA 含 wxwork;非企微环境无法静默授权,引导改用企微扫码。
const isWecomUA = computed(() =>
typeof navigator !== 'undefined' && /wxwork/i.test(navigator.userAgent || ''),
)
const iconState = computed(() => { const iconState = computed(() => {
if (state.value === 'success') return 'success' if (state.value === 'success') return 'success'
@@ -114,8 +129,7 @@ const iconState = computed(() => {
const title = computed(() => { const title = computed(() => {
switch (state.value) { switch (state.value) {
case 'boot': case 'boot':
case 'authing': return '正在打开签到页…'
return '正在进入签到…'
case 'ready': case 'ready':
return page.value?.already_signed ? '您已签到' : '培训签到' return page.value?.already_signed ? '您已签到' : '培训签到'
case 'submitting': case 'submitting':
@@ -130,31 +144,33 @@ const title = computed(() => {
const hint = computed(() => { const hint = computed(() => {
switch (state.value) { switch (state.value) {
case 'boot': case 'boot':
case 'authing': return '正在加载课程签到信息,请稍候'
return '正在验证身份并打开签到页,请稍候'
case 'ready': case 'ready':
return page.value?.already_signed if (page.value?.already_signed) return '本课程您已完成签到,无需重复操作'
? '本课程您已完成签到,无需重复操作' return needEmployeeNo.value ? '请输入本人工号并点击签到' : '请核对签到人信息,点击下方按钮完成签到'
: '请核对课程与签到人信息,点击下方按钮完成签到'
case 'submitting': case 'submitting':
return '正在获取定位并提交签到,请保持页面打开' return '正在获取定位并提交签到,请保持页面打开'
case 'success': case 'success':
return `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'},即将进入课程详情…` return authStore.isLoggedIn
? `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'},即将进入课程详情…`
: `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'}`
case 'blocked': case 'blocked':
return errorMsg.value || '请使用企业微信「扫一扫」扫描培训签到码' return errorMsg.value || '签到码无效或已过期,请重新扫码'
default: default:
return errorMsg.value || '签到失败,请重试' return errorMsg.value || '签到失败,请重试'
} }
}) })
// 错误态是否提供「重新签到」:仅瞬时失败(定位/网络/时间戳偏差)可重试; // 错误态是否提供「重新签到」:仅瞬时失败(定位/网络/工号笔误)可重试;
// 名单外/非当天/工号不一致属确定性拒绝,提示后不重试。 // 名单外/非当天/重复签到属确定性拒绝,提示后不重试。
const retryable = computed(() => { const retryable = computed(() => {
const msg = errorMsg.value const msg = errorMsg.value
return !(/名单|当天|已结束|尚未开始|工号|重复扫码|已签到/.test(msg)) return !(/名单|当天|已结束|尚未开始|重复扫码|已签到/.test(msg))
}) })
// ---- 落地页主体态(ready)按钮/提示 ---- // ---- 落地页主体态(ready) ----
// 匿名主流程:落地页未带成员信息(工号未输入),需学员手输工号。
const needEmployeeNo = computed(() => !page.value?.member)
const memberLabel = computed(() => { const memberLabel = computed(() => {
const m = page.value?.member const m = page.value?.member
if (!m) return '' if (!m) return ''
@@ -189,57 +205,47 @@ const signDisabled = computed(() => {
if (page.value.already_signed) return true if (page.value.already_signed) return true
if (remainSec.value <= 0) return true if (remainSec.value <= 0) return true
if (page.value.course && !page.value.course.can_sign_today) return true if (page.value.course && !page.value.course.can_sign_today) return true
if (needEmployeeNo.value && !employeeNoInput.value.trim()) return true
// 名单标记仅在身份已知(已登录/工号校验过)时用于置灰;匿名态交给提交强校验
if (page.value.member && !page.value.in_roster) return true
return false return false
}) })
const signDisabledReason = computed(() => { const signDisabledReason = computed(() => {
if (!page.value) return '' if (!page.value) return ''
if (page.value.already_signed) return '本课程您已完成签到' if (page.value.already_signed) return '本课程您已完成签到'
if (remainSec.value <= 0) return '签到码已过期,请用企业微信重新扫码' if (remainSec.value <= 0) return '签到码已过期,请重新扫码'
if (page.value.course && !page.value.course.can_sign_today) { if (page.value.course && !page.value.course.can_sign_today) {
const start = page.value.course.start_at ? fmtBeijingTime(page.value.course.start_at) : '' const start = page.value.course.start_at ? fmtBeijingTime(page.value.course.start_at) : ''
return `培训尚未开始(${start} 开课),培训当天再来签到` return `培训尚未开始(${start} 开课),培训当天再来签到`
} }
if (!page.value.in_roster) return '您不在该课程的「参加人员」名单中,请联系讲师或人事确认' if (page.value.member && !page.value.in_roster) return '您不在该课程的「参加人员」名单中,请联系讲师或人事确认'
return '' return ''
}) })
const signButtonText = computed(() => { const signButtonText = computed(() => {
if (page.value?.already_signed) return '已签到' if (page.value?.already_signed) return '已签到'
if (state.value === 'submitting') return '签到中…' if (state.value === 'submitting') return '签到中…'
return '点击签到' return needEmployeeNo.value ? '输入工号签到' : '点击签到'
}) })
// ---- 链路编排 ---- // ---- 登录态持久化(与 /auth/login 同构,复用 Login.vue 持久化路径) ----
type LoginPayload = {
// 企微 OAuth 静默授权跳转:snsapi_base,学员无感;回跳落地页带 code+state。 token?: string
const startOAuth = async () => { refresh_token?: string
state.value = 'authing' user?: Record<string, any>
try { active_tenant?: { id: number | string; name?: string; created_at?: string; updated_at?: string } | null
const res = unwrap<{ authorize_url: string }>( memberships?: Array<{ tenant_id: number; tenant_name?: string; role: string }>
await getCheckinAuthUrl(routeToken.value, `${window.location.origin}/platform/training/checkin/${routeToken.value}`),
)
if (!res?.authorize_url) throw new Error('empty authorize_url')
window.location.replace(res.authorize_url)
} catch (e: any) {
state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '免登跳转失败,请重新扫码'
}
} }
const persistLogin = (data: LoginPayload) => {
// OAuth 回跳:code 换平台会话(token/refresh_token/user/tenant/memberships,
// 与 /auth/login 同构)→ 复用登录持久化路径完成"签到即自动登录"。
const persistLogin = (data: WecomCheckinSessionData) => {
const activeTenant = data.active_tenant || null const activeTenant = data.active_tenant || null
const homeTenantIdRaw = (data.user as any)?.tenant_id ?? activeTenant?.id ?? '' const homeTenantIdRaw = data.user?.tenant_id ?? activeTenant?.id ?? ''
if (data.user) { if (data.user) authStore.setUser(userInfoFromApi(data.user, homeTenantIdRaw))
authStore.setUser(userInfoFromApi(data.user, homeTenantIdRaw)) authStore.setToken(data.token || '')
}
authStore.setToken(data.token)
if (data.refresh_token) authStore.setRefreshToken(data.refresh_token) if (data.refresh_token) authStore.setRefreshToken(data.refresh_token)
if (activeTenant) { if (activeTenant) {
authStore.setTenant({ authStore.setTenant({
id: String(activeTenant.id) || '', id: String(activeTenant.id) || '',
name: activeTenant.name || '', name: activeTenant.name || '',
owner_id: String((data.user as any)?.id || ''), owner_id: String(data.user?.id || ''),
created_at: activeTenant.created_at || new Date().toISOString(), created_at: activeTenant.created_at || new Date().toISOString(),
updated_at: activeTenant.updated_at || new Date().toISOString(), updated_at: activeTenant.updated_at || new Date().toISOString(),
}) })
@@ -257,10 +263,22 @@ const persistLogin = (data: WecomCheckinSessionData) => {
} }
} }
// ---- 链路编排 ----
const applyPage = (data: WecomCheckinPageData) => {
page.value = data
// 已登录且档案已知时预填工号,点击即签;匿名态由学员手输。
if (data.member?.employee_no && !employeeNoInput.value) {
employeeNoInput.value = data.member.employee_no
}
state.value = 'ready'
startCountdown()
}
// OAuth 回跳(预留通道):code 换会话并持久化(可信域名配置就绪后恢复)。
const exchangeSession = async (code: string, stateToken: string) => { const exchangeSession = async (code: string, stateToken: string) => {
state.value = 'authing'
try { try {
const data = unwrap<WecomCheckinSessionData>(await wecomCheckinSession(code, stateToken)) const data = unwrap<WecomCheckinByEmployeeData & LoginPayload>(await wecomCheckinSession(code, stateToken))
if (!data?.token) throw new Error('empty session token') if (!data?.token) throw new Error('empty session token')
persistLogin(data) persistLogin(data)
applyPage(data) applyPage(data)
@@ -268,30 +286,31 @@ const exchangeSession = async (code: string, stateToken: string) => {
window.history.replaceState(null, '', window.location.pathname) window.history.replaceState(null, '', window.location.pathname)
} catch (e: any) { } catch (e: any) {
state.value = 'blocked' state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '免登失败,请重新扫码' errorMsg.value = apiErrorMessage(e, '免登失败,请重新扫码')
} }
} }
const applyPage = (data: WecomCheckinPageData) => { // 已登录(PC 讲师自测/已有会话):取落地页数据并预填工号。
page.value = data
state.value = 'ready'
startCountdown()
}
// 已登录(PC 讲师自测 / 企微内已有会话):直接取落地页数据;token 失效时在
// 企微环境回退免登链路。
const loadPage = async () => { const loadPage = async () => {
try { try {
const data = unwrap<WecomCheckinPageData>(await wecomCheckinPage(routeToken.value)) const data = unwrap<WecomCheckinPageData>(await wecomCheckinPage(routeToken.value))
if (!data) throw new Error('empty page data') if (!data) throw new Error('empty page data')
applyPage(data) applyPage(data)
} catch (e: any) { } catch (e: any) {
if (isWecomUA.value) { // 登录态失效等:回退匿名主流程(工号手输),不阻塞签到。
await startOAuth() await loadAnonPage(e)
return }
} }
// 匿名主流程(扫码默认):未登录学员落地页,工号手输签到。
const loadAnonPage = async (presetErr?: any) => {
try {
const data = unwrap<WecomCheckinPageData>(await wecomCheckinPageAnon(routeToken.value))
if (!data) throw new Error('empty page data')
applyPage(data)
} catch (e: any) {
state.value = 'blocked' state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '签到码无效或已过期,请重新扫码' errorMsg.value = apiErrorMessage(e, '') || apiErrorMessage(presetErr, '签到码无效或已过期,请重新扫码')
} }
} }
@@ -315,34 +334,68 @@ const locate = () =>
) )
}) })
// 点击签到(2026-11 需求:不再进页自动签):工号 + 随机时间戳随请求提交, // 点击签到(需求:进页不自动签):工号 + 随机时间戳随请求提交,后端按规则
// 后端做当天性/名单硬校验与防重放。 // 校验(当天/名单硬拒/围栏/迟到/重复/nonce 防重放)。
const sign = async () => { const sign = async () => {
if (!page.value || signDisabled.value) return if (!page.value || signDisabled.value || state.value === 'submitting') return
const employeeNo = employeeNoInput.value.trim()
if (needEmployeeNo.value && !employeeNo) {
MessagePlugin.warning('请先输入工号')
return
}
state.value = 'submitting' state.value = 'submitting'
errorMsg.value = '' errorMsg.value = ''
await locate() await locate()
const nonce = `${Date.now()}${Math.random().toString(36).slice(2, 10)}` const nonce = `${Date.now()}${Math.random().toString(36).slice(2, 10)}`
try { try {
const res = unwrap<TrainingSignRecord>( if (needEmployeeNo.value) {
await checkin(routeToken.value, geo.value.lat, geo.value.lng, 'wecom_scan', '', { // 工号主流程:规则校验 + 工号反查档案 + 自动登录一次完成。
employee_no: page.value.member?.employee_no || '', const data = unwrap<WecomCheckinByEmployeeData>(
nonce, await wecomCheckinByEmployee({
client_ts: Date.now(), token: routeToken.value,
}), employee_no: employeeNo,
) nonce,
record.value = res || null lat: geo.value.lat,
state.value = 'success' lng: geo.value.lng,
stopCountdown() client_ts: Date.now(),
// 签到成功 → 已自动登录,稍作停留后进入该课程详情页(需求补充 3)。 }),
window.setTimeout(() => { )
if (page.value?.course_id) { record.value = data?.record || null
router.push(`/platform/training/course/${page.value.course_id}`) // 回填成员/课程信息(展示签到人行);自动登录关闭(token 空)时停留成功页。
if (data?.member) page.value = data
if (data?.token) {
persistLogin(data)
state.value = 'success'
window.setTimeout(() => {
if (page.value?.course_id) {
router.push(`/platform/training/course/${page.value.course_id}`)
}
}, 1800)
} else {
state.value = 'success'
} }
}, 1800) } else {
// 已登录路径(预填工号,走常规登录态签到接口,规则引擎同一套严格校验)。
const res = unwrap<TrainingSignRecord>(
await checkin(routeToken.value, geo.value.lat, geo.value.lng, 'wecom_scan', '', {
employee_no: employeeNo,
nonce,
client_ts: Date.now(),
}),
)
record.value = res || null
state.value = 'success'
window.setTimeout(() => {
if (page.value?.course_id) {
router.push(`/platform/training/course/${page.value.course_id}`)
}
}, 1800)
}
} catch (e: any) { } catch (e: any) {
state.value = 'error' state.value = 'error'
errorMsg.value = e?.response?.data?.message || '签到失败,请重试' // 000165 复测:透出后端具体原因(不在参加人员名单/工号无档案/当天性/防重放等),
// 不再落到通用「签到失败,请重试」(后端错误信封为 {error:{message}},手写取值取不到)
errorMsg.value = apiErrorMessage(e, '签到失败,请重试')
} }
} }
@@ -354,7 +407,7 @@ onMounted(() => {
const oauthCode = route.query.code ? String(route.query.code) : '' const oauthCode = route.query.code ? String(route.query.code) : ''
const oauthState = route.query.state ? String(route.query.state) : '' const oauthState = route.query.state ? String(route.query.state) : ''
if (oauthCode && oauthState) { if (oauthCode && oauthState) {
// 企微 OAuth 回跳:优先消费一次性 code 完成免登。 // 预留通道:企微 OAuth 回跳(URL 带 code+state 时才消费,当前主流程不走)。
exchangeSession(oauthCode, oauthState) exchangeSession(oauthCode, oauthState)
return return
} }
@@ -367,12 +420,8 @@ onMounted(() => {
loadPage() loadPage()
return return
} }
if (isWecomUA.value) { // 扫码默认:匿名主流程(课程信息 + 工号手输签到)。
startOAuth() loadAnonPage()
return
}
state.value = 'blocked'
errorMsg.value = '请使用企业微信「扫一扫」扫描培训签到码完成签到'
}) })
onBeforeUnmount(stopCountdown) onBeforeUnmount(stopCountdown)
@@ -383,8 +432,10 @@ onBeforeUnmount(stopCountdown)
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
min-height: 60vh; // 独立手机端 H5 页:顶层路由直接渲染,占满整屏并居中卡片(脱离平台壳布局)。
min-height: 100vh;
padding: var(--app-space-4); padding: var(--app-space-4);
background: var(--td-bg-color-page, #f3f3f3);
} }
.checkin-card { .checkin-card {
@@ -480,6 +531,17 @@ onBeforeUnmount(stopCountdown)
} }
} }
.emp-no-box {
width: 100%;
&__hint {
margin-top: 6px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm, 13px);
text-align: left;
}
}
.countdown { .countdown {
width: 100%; width: 100%;
padding: 8px 12px; padding: 8px 12px;
+25 -3
View File
@@ -13,6 +13,8 @@
</t-tag> </t-tag>
<h2 class="detail-name">{{ course?.name || '课程详情' }}</h2> <h2 class="detail-name">{{ course?.name || '课程详情' }}</h2>
<t-tag v-if="course" theme="default" variant="outline" size="small">{{ typeText }}</t-tag> <t-tag v-if="course" theme="default" variant="outline" size="small">{{ typeText }}</t-tag>
<!-- 课程下线(000163):关联课程管理条目已下线时标注并拦截学习入口 -->
<t-tag v-if="libraryOffline" theme="danger" variant="light" size="small">课程已下线</t-tag>
<!-- 培训签到:跳「培训签到」页并自动定位本课程场次(SignPanel 读取 courseId 查询参数) --> <!-- 培训签到:跳「培训签到」页并自动定位本课程场次(SignPanel 读取 courseId 查询参数) -->
<t-button v-if="course" variant="outline" theme="primary" size="small" class="detail-signin" @click="goSignin"> <t-button v-if="course" variant="outline" theme="primary" size="small" class="detail-signin" @click="goSignin">
培训签到 培训签到
@@ -53,8 +55,14 @@
<!-- 预览区 --> <!-- 预览区 -->
<main class="preview-pane"> <main class="preview-pane">
<t-loading :loading="previewLoading" class="preview-pane__inner" :fullscreen="false"> <t-loading :loading="previewLoading" class="preview-pane__inner" :fullscreen="false">
<!-- 课程已下线(000163):不能再打开学习,统一提示 -->
<t-empty
v-if="libraryOffline"
class="preview-empty"
description="该课程已下线,不能再继续学习;如有疑问请联系培训管理员"
/>
<DocumentPreview <DocumentPreview
v-if="current && docBlob" v-else-if="current && docBlob"
:source-blob="docBlob" :source-blob="docBlob"
:file-type="previewKind(current)" :file-type="previewKind(current)"
:file-name="current.name" :file-name="current.name"
@@ -71,8 +79,8 @@
</main> </main>
</div> </div>
<!-- 随堂考试(开启随堂考试或绑定题库即可考) --> <!-- 随堂考试(开启随堂考试或绑定题库即可考;课程已下线时不提供) -->
<div v-if="course?.exam_enabled || course?.exam_ready" class="panel-box exam-box"> <div v-if="!libraryOffline && (course?.exam_enabled || course?.exam_ready)" class="panel-box exam-box">
<div class="panel-box__header"> <div class="panel-box__header">
<span class="panel-box__title">随堂考试</span> <span class="panel-box__title">随堂考试</span>
<div class="panel-box__actions"> <div class="panel-box__actions">
@@ -182,6 +190,10 @@ const wrongCount = ref(0)
const typeText = computed(() => (course.value?.type === 'elective' ? '选修' : '必修')) const typeText = computed(() => (course.value?.type === 'elective' ? '选修' : '必修'))
// 课程已下线(000163):关联课程管理条目 publish_status=offline 时拦截学习
// (课件预览/进度上报/随堂考试统一提示「该课程已下线」;已有培训计划保留展示)
const libraryOffline = computed(() => Boolean(course.value?.library_offline))
const taskState = computed(() => { const taskState = computed(() => {
const map: Record<string, string> = { done: '已完成', doing: '学习中', overdue: '已逾期', pending: '待学习' } const map: Record<string, string> = { done: '已完成', doing: '学习中', overdue: '已逾期', pending: '待学习' }
return myTask.value ? map[myTask.value.status] || '' : '' return myTask.value ? map[myTask.value.status] || '' : ''
@@ -225,6 +237,10 @@ const stopHeartbeat = () => {
// 跨空间学员(培训数据在档案空间)会被 403「Permission denied」拦截;培训域 // 跨空间学员(培训数据在档案空间)会被 403「Permission denied」拦截;培训域
// 文件流按解析后的培训租户服务端取文件,与下载/和信课程抽屉同口径。 // 文件流按解析后的培训租户服务端取文件,与下载/和信课程抽屉同口径。
const openMaterial = async (m: TrainingMaterial) => { const openMaterial = async (m: TrainingMaterial) => {
if (libraryOffline.value) {
MessagePlugin.warning('该课程已下线,不能再继续学习')
return
}
if (current.value?.id === m.id) return if (current.value?.id === m.id) return
stopHeartbeat() stopHeartbeat()
current.value = m current.value = m
@@ -306,6 +322,10 @@ const bindVideoHeartbeat = () => {
// ---- 随堂考试 ---- // ---- 随堂考试 ----
const startExam = async () => { const startExam = async () => {
if (libraryOffline.value) {
MessagePlugin.warning('该课程已下线,不能再参加考试')
return
}
examLoading.value = true examLoading.value = true
try { try {
const data = unwrap<{ paper: TrainingPaper; questions: TrainingQuestion[] }>(await getCourseExamPaper(courseId)) const data = unwrap<{ paper: TrainingPaper; questions: TrainingQuestion[] }>(await getCourseExamPaper(courseId))
@@ -377,6 +397,8 @@ const loadAll = async () => {
const exam = r && unwrap<{ record: TrainingExamRecord | null; passed: boolean }>(r) const exam = r && unwrap<{ record: TrainingExamRecord | null; passed: boolean }>(r)
examRecord.value = exam?.record || null examRecord.value = exam?.record || null
examPassed.value = !!exam?.passed examPassed.value = !!exam?.passed
// 课程已下线(000163):不自动打开课件,页面统一展示「该课程已下线」
if (libraryOffline.value) return
// [2026-11 需求] 进入有课件的课程默认打开第一个课件,免手动从左侧选择 // [2026-11 需求] 进入有课件的课程默认打开第一个课件,免手动从左侧选择
if (materials.value.length) void openMaterial(materials.value[0]) if (materials.value.length) void openMaterial(materials.value[0])
} finally { } finally {
+5 -5
View File
@@ -124,15 +124,15 @@ const isAdmin = computed(() =>
myRoles.value.some((r) => r === 'hr') || myRoles.value.some((r) => r === 'hr') ||
authStore.hasRole('admin')) authStore.hasRole('admin'))
// 培训管理页签(培训计划/培训课程/培训签到)门槛:课长/经理/人事/讲师 // 培训管理页签(培训计划/培训课程/培训签到)门槛:课长/经理/人事/讲师/超级管理员
// (myRoles 已按权限组展开,自定义角色继承系统角色后自动生效)。 // (myRoles 已按权限组展开,自定义角色继承系统角色后自动生效)。
const canManageTabs = computed(() => const canManageTabs = computed(() =>
isAdmin.value || isAdmin.value ||
myRoles.value.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r))) myRoles.value.some((r) => ['hr', 'supervisor', 'exec', 'lecturer', 'super_admin'].includes(r)))
// 配置中心门槛(000158):人事/空间管理员之外,经理职称角色同权查看与维护。 // 配置中心门槛(000163 权限收口):仅平台超级管理员可查看与维护
const canManageConfig = computed(() => // (菜单入口/路由守卫同步收口,此处为页面内兜底)。
isAdmin.value || myRoles.value.some((r) => r === 'exec')) const canManageConfig = computed(() => authStore.isSystemAdmin)
// 页头角色标签:展示实际分配的角色(非权限展开),文案取自配置中心字典 // 页头角色标签:展示实际分配的角色(非权限展开),文案取自配置中心字典
const myRoleLabel = computed(() => const myRoleLabel = computed(() =>
@@ -38,7 +38,7 @@
<!-- 我的考试:与我相关的考试记录列表(000154) --> <!-- 我的考试:与我相关的考试记录列表(000154) -->
<t-loading v-if="filter === 'exam'" :loading="loading" class="catalog-grid-wrap"> <t-loading v-if="filter === 'exam'" :loading="loading" class="catalog-grid-wrap">
<t-table :data="examRows" :columns="examColumns" row-key="id" size="small"> <t-table :data="pagedExamRows" :columns="examColumns" row-key="id" size="small">
<template #course_name="{ row }">{{ row.course_name || row.paper_name || '-' }}</template> <template #course_name="{ row }">{{ row.course_name || row.paper_name || '-' }}</template>
<template #score="{ row }"> <template #score="{ row }">
<span :class="row.passed ? 'exam-score is-good' : 'exam-score is-bad'">{{ row.score ?? '—' }}</span> <span :class="row.passed ? 'exam-score is-good' : 'exam-score is-bad'">{{ row.score ?? '—' }}</span>
@@ -46,6 +46,7 @@
<template #pass_line="{ row }">{{ row.pass_score || '-' }} / {{ row.total_score || '-' }}</template> <template #pass_line="{ row }">{{ row.pass_score || '-' }} / {{ row.total_score || '-' }}</template>
<template #submitted_at="{ row }">{{ fmtExamTime(row.submitted_at) }}</template> <template #submitted_at="{ row }">{{ fmtExamTime(row.submitted_at) }}</template>
</t-table> </t-table>
<TrainingPagination v-model:current="examPage" v-model:page-size="examPageSize" :total="examTotal" />
<t-empty v-if="!loading && !examRows.length" class="catalog-empty" description="暂无考试记录,参加随堂考试后此处展示成绩" /> <t-empty v-if="!loading && !examRows.length" class="catalog-empty" description="暂无考试记录,参加随堂考试后此处展示成绩" />
</t-loading> </t-loading>
@@ -53,7 +54,7 @@
<t-loading v-else :loading="loading" class="catalog-grid-wrap"> <t-loading v-else :loading="loading" class="catalog-grid-wrap">
<div class="catalog-grid"> <div class="catalog-grid">
<article <article
v-for="card in visibleCards" v-for="card in pagedCards"
:key="card.id" :key="card.id"
class="course-card" class="course-card"
role="link" role="link"
@@ -98,15 +99,18 @@
<t-empty <t-empty
v-if="!loading && !visibleCards.length" v-if="!loading && !visibleCards.length"
class="catalog-empty" class="catalog-empty"
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'" :description="emptyText"
/> />
<!-- 共用分页(000163):课程卡片默认每页 15 条 -->
<TrainingPagination v-model:current="cardPage" v-model:page-size="cardPageSize" :total="cardTotal" />
</t-loading> </t-loading>
<!-- 课程学习抽屉(000160):和信课程卡片点开即学 —— 课件在线预览 + 下载 --> <!-- 课程学习抽屉(000160):和信课程卡片点开即学 —— 课件在线预览 + 下载
000165 复测:展示区域放大(72% 宽,预览随抽屉高度撑满) -->
<t-drawer <t-drawer
v-model:visible="learningVisible" v-model:visible="learningVisible"
:header="learningCourse?.name || '课程学习'" :header="learningCourse?.name || '课程学习'"
size="860px" size="72%"
:footer="false" :footer="false"
> >
<div v-if="learningCourse" class="course-learning"> <div v-if="learningCourse" class="course-learning">
@@ -146,10 +150,12 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
import DocumentPreview from '@/components/document-preview.vue' import DocumentPreview from '@/components/document-preview.vue'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
import { import {
downloadCourseLibraryMaterial, downloadCourseLibraryMaterial,
getMyProfile, getMyProfile,
@@ -260,28 +266,26 @@ const FILTERS = [
// 工作台进目录默认落在「我的培训」(与我相关的课优先展示) // 工作台进目录默认落在「我的培训」(与我相关的课优先展示)
const filter = ref<string>('mine') const filter = ref<string>('mine')
const keyword = ref('') const keyword = ref('')
// 和信课程目录加载失败标记:目录查询异常(如服务版本与数据库迁移不一致)时
// 空态给出明确提示,不再静默显示「暂无课程」误导排查方向
const catalogLoadFailed = ref(false)
// 目录空态文案:按页签与加载状态区分(加载失败时优先提示)
const emptyText = computed(() => {
if (filter.value !== 'mine' && filter.value !== 'exam' && catalogLoadFailed.value) {
return '课程目录加载失败,请刷新重试;若持续出现请联系管理员检查服务版本与数据库迁移'
}
return filter.value === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'
})
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护) // 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published')) const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
// 「和信课程」(000160):已发布 + 适合人员覆盖查看人 —— 「全部」全员可见; // 「和信课程」(000160):已发布课程目录。课程权限(000163)由后端 scope=catalog
// 000159 多部门口径:值按「、」拆分(逗号/分号兼容归一)后与查看人部门名做 // 按调用方部门/人员统一过滤,此处只保留发布状态过滤 —— 不再做客户端权限复算:
// 成员匹配;未设置适合人员的存量课程沿用原部门范围口径(所属部门为空 = 全员, // 此前按我的档案部门/用户 id 复算,调用方档案缺部门(或 id 口径不一致)时会把
// 否则须与我的部门一致)。后端 scope=catalog 已按同口径过滤,此处保留客户端兜底。 // 服务端已授权的课程误杀,表现为「审核通过后和信课程看不到」(2026-11-26 复测修复)。
const myDeptId = computed(() => myProfile.value?.dept_id || '')
const myDeptName = computed(() => (myProfile.value?.dept_name || '').trim())
const hexinCourses = computed<TrainingLibraryCourse[]>(() => const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
libraryItems.value.filter((c) => { libraryItems.value.filter((c) => c.publish_status === 'published'),
if (c.publish_status !== 'published') return false
const suitableNames = (c.suitable_members || '')
.split(/[、,,;;]/)
.map((s) => s.trim())
.filter(Boolean)
if (suitableNames.length) {
return suitableNames.includes('全部') || (!!myDeptName.value && suitableNames.includes(myDeptName.value))
}
return !c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value
}),
) )
const statsText = computed(() => { const statsText = computed(() => {
@@ -558,8 +562,30 @@ const visibleCards = computed<CatalogCard[]>(() => {
}) })
}) })
// 共用分页(000163):我的考试记录与课程卡片默认每页 15 条;搜索/页签切换后回到第 1 页
const {
page: examPage,
pageSize: examPageSize,
total: examTotal,
paged: pagedExamRows,
reset: resetExamPage,
} = useTrainingPager(examRows)
const {
page: cardPage,
pageSize: cardPageSize,
total: cardTotal,
paged: pagedCards,
reset: resetCardPage,
} = useTrainingPager(visibleCards)
watch([examRows, visibleCards, filter], () => {
resetExamPage()
resetCardPage()
})
const loadAll = async () => { const loadAll = async () => {
loading.value = true loading.value = true
catalogLoadFailed.value = false
try { try {
// 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 id 过滤), // 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 id 过滤),
// 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。 // 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
@@ -571,9 +597,14 @@ const loadAll = async () => {
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null), listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
getMyProfile().catch(() => null), getMyProfile().catch(() => null),
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null), needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
// 和信课程目录(000160):scope=catalog —— 已发布 + 适合人员覆盖查看人 // 和信课程目录(000160):scope=catalog —— 已发布 + 课程权限覆盖查看人
// (全部/本部门;未设置沿用部门范围口径),不按维护角色收窄,全体员工同源 // (000163 部门/人员 id 精确匹配;存量课程沿用老口径),后端按权限过滤
listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => null), listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => {
// 目录查询失败不再静默吞成「暂无课程」(此前服务版本与数据库迁移不一致
// 时表现为「审核通过后和信课程看不到」且无任何提示,2026-11-26 复测修复)
catalogLoadFailed.value = true
return null
}),
// 我的考试记录(000154) // 我的考试记录(000154)
listMyExamRecords().catch(() => null), listMyExamRecords().catch(() => null),
// 我经场次学员名单报名的课程 id(「我参加」判定;旧后端无此接口时回退空集) // 我经场次学员名单报名的课程 id(「我参加」判定;旧后端无此接口时回退空集)
@@ -721,22 +752,58 @@ onMounted(loadAll)
} }
// 课程学习抽屉(000160):元信息行 + 预览主体 + 下载操作 // 课程学习抽屉(000160):元信息行 + 预览主体 + 下载操作
// 000165 复测:预览区撑满抽屉 —— 抽屉 body 拉成 flex 纵向布局,课程内容块
// 撑满剩余高度(此前仅 min-height:100%,document-preview 的 height:100% 在
// auto 高度链上不生效,预览塌陷为固定小窗)
.course-catalog :deep(.t-drawer__body) {
display: flex;
flex-direction: column;
overflow: auto;
}
.course-learning { .course-learning {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
min-height: 100%; flex: 1;
min-height: 0;
// t-loading 组件包装层的真实 DOM 类是 t-loading__parent > t-loading__content
// (此前误写 .t-loading 未命中,高度链断裂预览塌陷),拉成纵向 flex 撑满
:deep(.t-loading__parent) {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
.t-loading__content {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
}
// 兜底:预览组件给确定性高度(视口 - 抽屉头/元信息/按钮行/留白),
// 即使 flex 高度链断裂也满屏,底部仅保留「下载课件」按钮一行高度
:deep(.document-preview) {
flex: 1;
min-height: 0;
height: calc(100vh - 210px);
}
&__meta { &__meta {
margin: 0; margin: 0;
color: var(--td-text-color-secondary); color: var(--td-text-color-secondary);
font-size: 13px; font-size: 13px;
flex: none;
} }
&__actions { &__actions {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
gap: 8px; gap: 8px;
flex: none;
} }
} }
@@ -59,7 +59,7 @@
</div> </div>
<t-table <t-table
:data="filteredRows" :data="pagedRows"
:columns="learnColumns" :columns="learnColumns"
row-key="id" row-key="id"
size="small" size="small"
@@ -74,6 +74,8 @@
<t-tag :theme="taskTheme(row.status)" variant="light" size="small">{{ taskText(row.status) }}</t-tag> <t-tag :theme="taskTheme(row.status)" variant="light" size="small">{{ taskText(row.status) }}</t-tag>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="rowPage" v-model:page-size="rowPageSize" :total="rowTotal" />
<t-empty v-if="!courseId" description="选择课程后查看该课程全员学习进度" /> <t-empty v-if="!courseId" description="选择课程后查看该课程全员学习进度" />
<t-empty v-else-if="!taskLoading && !rows.length" description="该课程暂无学习任务" /> <t-empty v-else-if="!taskLoading && !rows.length" description="该课程暂无学习任务" />
<t-empty v-else-if="rows.length && !filteredRows.length" description="没有符合查询条件的记录" /> <t-empty v-else-if="rows.length && !filteredRows.length" description="没有符合查询条件的记录" />
@@ -92,6 +94,8 @@ import {
unwrap, unwrap,
} from '@/api/training' } from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
// 课程学习情况(管理端):列表按课程+学员唯一(后端 tr_learning_tasks // 课程学习情况(管理端):列表按课程+学员唯一(后端 tr_learning_tasks
// 以 tenant+course+member 唯一索引约束),上方为各状态汇总,支持条件查询。 // 以 tenant+course+member 唯一索引约束),上方为各状态汇总,支持条件查询。
@@ -151,6 +155,17 @@ const filteredRows = computed(() => {
}) })
}) })
// 共用分页(000163):学习情况列表默认每页 15 条;条件查询/切换课程后回到第 1 页
const {
page: rowPage,
pageSize: rowPageSize,
total: rowTotal,
paged: pagedRows,
reset: resetRowPage,
} = useTrainingPager(filteredRows)
watch(filteredRows, resetRowPage)
const resetFilters = () => { const resetFilters = () => {
filters.dept = '' filters.dept = ''
filters.keyword = '' filters.keyword = ''
File diff suppressed because it is too large. Load diff
@@ -44,7 +44,7 @@
<span class="records-header__title">试卷</span> <span class="records-header__title">试卷</span>
<span class="muted">学员可在企微内答题;此处支持本人在线答题与监考代录</span> <span class="muted">学员可在企微内答题;此处支持本人在线答题与监考代录</span>
</div> </div>
<t-table :data="papers" :columns="paperColumns" row-key="id" size="small" :loading="papersLoading"> <t-table :data="pagedPapers" :columns="paperColumns" row-key="id" size="small" :loading="papersLoading">
<template #course="{ row }">{{ paperCourseName(row) }}</template> <template #course="{ row }">{{ paperCourseName(row) }}</template>
<template #op="{ row }"> <template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="onTakeExam(row)">答题</t-button> <t-button variant="text" theme="primary" size="small" @click="onTakeExam(row)">答题</t-button>
@@ -52,6 +52,7 @@
<t-button variant="text" size="small" @click="recordPaperId = row.id">考试情况</t-button> <t-button variant="text" size="small" @click="recordPaperId = row.id">考试情况</t-button>
</template> </template>
</t-table> </t-table>
<TrainingPagination v-model:current="paperPage" v-model:page-size="paperPageSize" :total="paperTotal" />
<t-empty v-if="!papersLoading && !papers.length" description="该课程暂无试卷(组卷/AI 生成/答题后自动生成)" /> <t-empty v-if="!papersLoading && !papers.length" description="该课程暂无试卷(组卷/AI 生成/答题后自动生成)" />
</template> </template>
@@ -93,7 +94,7 @@
<span class="query-bar__hit">共 {{ filteredRecords.length }} 条</span> <span class="query-bar__hit">共 {{ filteredRecords.length }} 条</span>
</div> </div>
<t-table :data="filteredRecords" :columns="recordColumns" row-key="id" size="small" class="records-table" :loading="recordLoading"> <t-table :data="pagedRecords" :columns="recordColumns" row-key="id" size="small" class="records-table" :loading="recordLoading">
<template #member="{ row }">{{ memberLabel(row.member_id) }}</template> <template #member="{ row }">{{ memberLabel(row.member_id) }}</template>
<template #dept="{ row }">{{ memberDept(row.member_id) }}</template> <template #dept="{ row }">{{ memberDept(row.member_id) }}</template>
<template #score="{ row }"> <template #score="{ row }">
@@ -101,6 +102,7 @@
</template> </template>
<template #submitted_at="{ row }">{{ fmtTime(row.submitted_at) }}</template> <template #submitted_at="{ row }">{{ fmtTime(row.submitted_at) }}</template>
</t-table> </t-table>
<TrainingPagination v-model:current="recordPage" v-model:page-size="recordPageSize" :total="recordTotal" />
<t-empty v-if="!recordPaperId" description="选择课程与试卷后查看考试情况与答题记录" /> <t-empty v-if="!recordPaperId" description="选择课程与试卷后查看考试情况与答题记录" />
<t-empty v-else-if="!recordLoading && !records.length" description="该试卷暂无答题记录" /> <t-empty v-else-if="!recordLoading && !records.length" description="该试卷暂无答题记录" />
<t-empty v-else-if="records.length && !filteredRecords.length" description="没有符合查询条件的记录" /> <t-empty v-else-if="records.length && !filteredRecords.length" description="没有符合查询条件的记录" />
@@ -171,6 +173,8 @@ import {
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
import { apiErrorMessage } from '@/utils/request' import { apiErrorMessage } from '@/utils/request'
import QuestionExamDialog from './QuestionExamDialog.vue' import QuestionExamDialog from './QuestionExamDialog.vue'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
const props = defineProps<{ roles: string[]; admin?: boolean; initialCourseId?: string }>() const props = defineProps<{ roles: string[]; admin?: boolean; initialCourseId?: string }>()
// 监考/代交卷:人事/课长/讲师(roles 已按权限组展开,经理自动命中) // 监考/代交卷:人事/课长/讲师(roles 已按权限组展开,经理自动命中)
@@ -311,6 +315,19 @@ const filteredRecords = computed(() => {
}) })
}) })
// 共用分页(000163):试卷/考试成绩列表默认每页 15 条
const { page: paperPage, pageSize: paperPageSize, total: paperTotal, paged: pagedPapers } = useTrainingPager(papers)
const {
page: recordPage,
pageSize: recordPageSize,
total: recordTotal,
paged: pagedRecords,
reset: resetRecordPage,
} = useTrainingPager(filteredRecords)
// 条件查询/切换试卷后考试成绩回到第 1 页
watch(filteredRecords, resetRecordPage)
const loadAll = async () => { const loadAll = async () => {
const [s, m, c, d] = await Promise.all([ const [s, m, c, d] = await Promise.all([
listSessions({ page_size: 200 }), listSessions({ page_size: 200 }),
File diff suppressed because it is too large. Load diff
@@ -36,54 +36,57 @@
clearable clearable
placeholder="课程名称模糊搜索" placeholder="课程名称模糊搜索"
style="width: 200px" style="width: 200px"
@enter="loadDemands" @enter="onSearchDemands"
/> />
<t-button variant="outline" @click="loadDemands">查询</t-button> <t-button variant="outline" @click="onSearchDemands">查询</t-button>
<t-button variant="outline" @click="onResetDemandSearch">重置</t-button> <t-button variant="outline" @click="onResetDemandSearch">重置</t-button>
<t-button v-if="canConfirm" 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> <t-button v-if="canManage || isSuperAdmin" theme="danger" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchDelete">批量删除</t-button>
<span class="demand-selected-hint">已选 {{ selectedDemandKeys.length }} 项(可批量确认/删除未确认需求)</span> <span class="demand-selected-hint">已选 {{ selectedDemandKeys.length }} 项(可批量确认/删除未确认需求{{ isSuperAdmin ? ';超级管理员可删除已确认需求' : '' }})</span>
</div> </div>
<t-table <!-- 表格滚动区:面板满屏,筛选/表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
v-model:selected-row-keys="selectedDemandKeys" <div class="table-scroll">
:data="demands" <t-table
:columns="demandColumns" v-model:selected-row-keys="selectedDemandKeys"
row-key="id" :data="pagedDemands"
size="small" :columns="demandColumns"
:loading="loading" row-key="id"
> size="small"
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template> height="100%"
<template #code="{ row }"> :loading="loading"
<t-tooltip v-if="row.code" :content="row.code"> >
<span class="cell-ellipsis">{{ row.code }}</span> <template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
</t-tooltip> <template #code="{ row }">
<span v-else>-</span> <t-tooltip v-if="row.code" :content="row.code">
</template> <span class="cell-ellipsis">{{ row.code }}</span>
<template #lecturer_name="{ row }">{{ row.lecturer_name || '-' }}</template> </t-tooltip>
<!-- 计划培训月份入库格式「YYYY-M」(如 2027-1),原样展示 --> <span v-else>-</span>
<template #planned_time="{ row }">{{ row.planned_time || '-' }}</template> </template>
<template #location="{ row }">{{ row.location || '-' }}</template> <template #lecturer_name="{ row }">{{ row.lecturer_name || '-' }}</template>
<!-- 适合人员/备注可能很长:单行省略,悬停浮出全部内容 --> <!-- 计划培训月份入库格式「YYYY-M」(如 2027-1),原样展示 -->
<template #post_scope="{ row }"> <template #planned_time="{ row }">{{ row.planned_time || '-' }}</template>
<t-tooltip v-if="row.post_scope" :content="row.post_scope"> <template #location="{ row }">{{ row.location || '-' }}</template>
<span class="cell-ellipsis">{{ row.post_scope }}</span> <!-- 适合人员/备注可能很长:单行省略,悬停浮出全部内容 -->
</t-tooltip> <template #post_scope="{ row }">
<span v-else>-</span> <t-tooltip v-if="row.post_scope" :content="row.post_scope">
</template> <span class="cell-ellipsis">{{ row.post_scope }}</span>
<template #remark="{ row }"> </t-tooltip>
<t-tooltip v-if="row.remark" :content="row.remark"> <span v-else>-</span>
<span class="cell-ellipsis">{{ row.remark }}</span> </template>
</t-tooltip> <template #remark="{ row }">
<span v-else>-</span> <t-tooltip v-if="row.remark" :content="row.remark">
</template> <span class="cell-ellipsis">{{ row.remark }}</span>
<!-- 创建人(提报人姓名)/创建时间:记录需求由谁何时录入 --> </t-tooltip>
<template #submitter_name="{ row }">{{ row.submitter_name || '-' }}</template> <span v-else>-</span>
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template> </template>
<template #check_status="{ row }"> <!-- 创建人(提报人姓名)/创建时间:记录需求由谁何时录入 -->
<t-tag v-if="row.check_status === 'passed'" theme="success" variant="light" size="small">已确认</t-tag> <template #submitter_name="{ row }">{{ row.submitter_name || '-' }}</template>
<t-tag v-else-if="row.check_status === 'pending'" theme="warning" variant="light" size="small">待核验</t-tag> <template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
<t-tag v-else theme="default" variant="light" size="small">已修正</t-tag> <template #check_status="{ row }">
</template> <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 theme="default" variant="light" size="small">已修正</t-tag>
</template>
<template #op="{ row }"> <template #op="{ row }">
<template v-if="row.status !== 'confirmed'"> <template v-if="row.status !== 'confirmed'">
<t-button <t-button
@@ -97,8 +100,18 @@
<t-button variant="text" theme="danger" size="small">删除</t-button> <t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm> </t-popconfirm>
</template> </template>
<!-- 已确认需求纳入年度排期,普通角色不可删;超级管理员职称角色放开终态删除 -->
<t-popconfirm
v-else-if="isSuperAdmin"
content="该需求已确认,删除后不可恢复,确定删除?" theme="danger" @confirm="onDeleteDemand(row)"
>
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
</template> </template>
</t-table> </t-table>
</div>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="demandPage" v-model:page-size="demandPageSize" :total="demandTotal" />
</div> </div>
<!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) --> <!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) -->
@@ -250,6 +263,8 @@ import * as XLSX from 'xlsx'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
import { DEMAND_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates' import { DEMAND_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
import { apiErrorMessage } from '@/utils/request' import { apiErrorMessage } from '@/utils/request'
import TrainingPagination from './TrainingPagination.vue'
import { plannedMonthSortKey, useTrainingPager } from './useTrainingPager'
import { import {
broadcastTrainingNotification, broadcastTrainingNotification,
confirmDemand, confirmDemand,
@@ -291,7 +306,10 @@ const currentYear = now.getFullYear()
// 年度需求收集:年份下拉为需求库实际年份(降序),默认展示最新一年(无数据回退当前年) // 年度需求收集:年份下拉为需求库实际年份(降序),默认展示最新一年(无数据回退当前年)
const selectedYear = ref(currentYear) const selectedYear = ref(currentYear)
const yearOptions = ref<number[]>([]) const yearOptions = ref<number[]>([])
const onYearChange = () => loadDemands() const onYearChange = () => {
resetDemandPage()
loadDemands()
}
const loading = ref(false) const loading = ref(false)
const saving = ref(false) const saving = ref(false)
@@ -308,13 +326,15 @@ const myDeptId = ref('')
// 本部门课程(000156):课程名称下拉仅列所属部门课程——新建按提报人部门, // 本部门课程(000156):课程名称下拉仅列所属部门课程——新建按提报人部门,
// 编辑按需求归属部门(人事代改他部门需求时同样联动);部门为空回退全部课程 // 编辑按需求归属部门(人事代改他部门需求时同样联动);部门为空回退全部课程
// (000163:已下线课程不能再被需求选用,存量需求行不受影响)
const selectableCourses = computed(() => libraryCourses.value.filter((c) => c.publish_status !== 'offline'))
const deptCourseOptions = computed(() => { const deptCourseOptions = computed(() => {
const deptId = demandForm.value.id const deptId = demandForm.value.id
? demands.value.find((d) => d.id === demandForm.value.id)?.dept_id || myDeptId.value ? demands.value.find((d) => d.id === demandForm.value.id)?.dept_id || myDeptId.value
: myDeptId.value : myDeptId.value
return deptId return deptId
? libraryCourses.value.filter((c) => c.owner_dept_id === deptId) ? selectableCourses.value.filter((c) => c.owner_dept_id === deptId)
: libraryCourses.value : selectableCourses.value
}) })
const demandFormVisible = ref(false) const demandFormVisible = ref(false)
@@ -366,9 +386,11 @@ const onDemandCourseChange = (name: unknown) => {
const course = libraryCourses.value.find((c) => c.name === name) const course = libraryCourses.value.find((c) => c.name === name)
if (!course) return if (!course) return
demandForm.value.category = course.category || '' demandForm.value.category = course.category || ''
if (course.suitable_members) { // 适合人员(000165):优先课程管理备注字段 post_scope,存量课程回退 suitable_members
demandForm.value.post_scope = course.suitable_members const suitableValue = course.post_scope || course.suitable_members || ''
demandSuitableList.value = splitSuitable(course.suitable_members) if (suitableValue) {
demandForm.value.post_scope = suitableValue
demandSuitableList.value = splitSuitable(suitableValue)
} }
const lecturerValue = course.lecturer_id || course.lecturer_external || '' const lecturerValue = course.lecturer_id || course.lecturer_external || ''
if (lecturerValue) { if (lecturerValue) {
@@ -412,8 +434,14 @@ const deptDisplay = computed(() => {
return myDeptName.value return myDeptName.value
}) })
const demandColumns = [ // 超级管理员职称角色(super_admin):终态数据(已确认需求等)删除权唯一入口;
{ colKey: 'row-select', type: 'multiple', width: 44, disabled: ({ row }: { row: TrainingDemand }) => row.status === 'confirmed' }, // roles 已按权限组展开,自定义角色继承「超级管理员」权限组后同样命中
const isSuperAdmin = computed(() => props.roles.includes('super_admin'))
// 已确认行默认禁止勾选(批量确认/删除仅作用于未确认需求);超级管理员可勾选
// 以批量删除,故勾选禁用按角色动态计算(computed 随 props.roles 就绪刷新)
const demandColumns = computed(() => [
{ colKey: 'row-select', type: 'multiple', width: 44, disabled: ({ row }: { row: TrainingDemand }) => row.status === 'confirmed' && !isSuperAdmin.value },
// 年计划编号(AP-<year>-####,创建时由服务端生成) // 年计划编号(AP-<year>-####,创建时由服务端生成)
{ colKey: 'code', title: '编号', width: 130 }, { colKey: 'code', title: '编号', width: 130 },
{ colKey: 'course_name', title: '课程名称' }, { colKey: 'course_name', title: '课程名称' },
@@ -430,7 +458,7 @@ const demandColumns = [
// 状态/操作固定在列表右侧,横向滚动时始终可见 // 状态/操作固定在列表右侧,横向滚动时始终可见
{ colKey: 'check_status', title: '状态', width: 84, fixed: 'right' }, { colKey: 'check_status', title: '状态', width: 84, fixed: 'right' },
{ colKey: 'op', title: '操作', width: 160, fixed: 'right' }, { colKey: 'op', title: '操作', width: 160, fixed: 'right' },
] ])
// 批量确认/删除(仅作用于未确认需求,已确认行不可勾选) // 批量确认/删除(仅作用于未确认需求,已确认行不可勾选)
const selectedDemandKeys = ref<string[]>([]) const selectedDemandKeys = ref<string[]>([])
@@ -473,9 +501,11 @@ const onBatchConfirm = async () => {
} }
const onBatchDelete = async () => { const onBatchDelete = async () => {
const rows = demands.value.filter((d) => selectedDemandKeys.value.includes(d.id) && d.status !== 'confirmed') // 勾选口径:未确认行全员可勾;已确认行仅超级管理员可勾(isSuperAdmin 放开勾选),
// 后端按行校验终态删除权,越权行整批报错提示
const rows = demands.value.filter((d) => selectedDemandKeys.value.includes(d.id))
if (!rows.length) { if (!rows.length) {
MessagePlugin.warning('请先勾选未确认的需求') MessagePlugin.warning('请先勾选要删除的需求')
return return
} }
batchSaving.value = true batchSaving.value = true
@@ -512,9 +542,21 @@ const buildDemandQuery = () => {
const loadDemands = async () => { const loadDemands = async () => {
const d = await listDemands(buildDemandQuery()) const d = await listDemands(buildDemandQuery())
demands.value = unwrap(d)?.items || [] // 000163:按计划培训月份倒序(2027-12 → 2027-1,无计划培训时间的排最后)
const items = (unwrap(d)?.items || []) as TrainingDemand[]
demands.value = items.slice()
.sort((a, b) => plannedMonthSortKey(b.planned_time) - plannedMonthSortKey(a.planned_time))
} }
// 共用分页(000163):需求列表默认每页 15 条;查询条件/年度切换后回到第 1 页
const {
page: demandPage,
pageSize: demandPageSize,
total: demandTotal,
paged: pagedDemands,
reset: resetDemandPage,
} = useTrainingPager(demands)
// 年份下拉数据源:需求库实际年份(降序)。resetSelection=true 时默认选中最新一年 // 年份下拉数据源:需求库实际年份(降序)。resetSelection=true 时默认选中最新一年
// (首次进入);后续刷新仅在当前选中年份已无数据时回退最新,避免打断用户选择。 // (首次进入);后续刷新仅在当前选中年份已无数据时回退最新,避免打断用户选择。
const loadDemandYears = async (resetSelection = false) => { const loadDemandYears = async (resetSelection = false) => {
@@ -531,6 +573,13 @@ const loadDemandYears = async (resetSelection = false) => {
const onResetDemandSearch = () => { const onResetDemandSearch = () => {
demandSearch.value = { state: '', dept_id: '', keyword: '' } demandSearch.value = { state: '', dept_id: '', keyword: '' }
resetDemandPage()
loadDemands()
}
// 查询/年度切换:过滤条件变化后需求列表回到第 1 页
const onSearchDemands = () => {
resetDemandPage()
loadDemands() loadDemands()
} }
@@ -1010,6 +1059,17 @@ onMounted(() => {
} }
} }
// 表单项内提示文案(form-hint)统一另起一行展示在控件下方
.plan-panel {
.training-form-hints-below();
}
// 满屏列表布局(000164):页头固定,面板占满页身剩余高度,
// 筛选区/表头/分页固定,仅表格数据区滚动
.plan-panel {
.training-fill-panel();
}
// 已确认行不做整行置灰:t-table 行选择列 disabled 命中时会加 __row--disabled // 已确认行不做整行置灰:t-table 行选择列 disabled 命中时会加 __row--disabled
// 类(整行 text-color-disabled),业务上已确认行仅禁止勾选,文字保持正常色 // 类(整行 text-color-disabled),业务上已确认行仅禁止勾选,文字保持正常色
:deep(.t-table__row--disabled) { :deep(.t-table__row--disabled) {
@@ -1052,8 +1052,30 @@ watch(pushScene, () => loadPushLogs())
display: none; display: none;
} }
// ---- tab 化布局:tab 内容区与 panel-box 间距 ---- // ---- tab 化布局:页头与页签条固定,仅 tab 内容区滚动(000164 布局诉求) ----
.rule-panel {
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
}
.rule-tabs { .rule-tabs {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
:deep(.t-tabs__header) {
flex-shrink: 0;
}
:deep(.t-tabs__content) {
flex: 1;
min-height: 0;
overflow-y: auto;
}
:deep(.t-tab-panel) { :deep(.t-tab-panel) {
padding: 12px 0 0; padding: 12px 0 0;
} }
@@ -28,9 +28,15 @@
<img v-if="signQrUrl" :src="signQrUrl" class="sign-code-box__qr" alt="培训签到二维码" /> <img v-if="signQrUrl" :src="signQrUrl" class="sign-code-box__qr" alt="培训签到二维码" />
<div class="sign-code-box__token">{{ signCode?.token || '尚未生成' }}</div> <div class="sign-code-box__token">{{ signCode?.token || '尚未生成' }}</div>
<div class="sign-code-box__meta" v-if="signCode"> <div class="sign-code-box__meta" v-if="signCode">
有效期至 {{ fmtTime(signCode.expire_at) }} <!-- 文案口径(测试反馈 2026-11-26):「二维码有效期至 HH:mm」,不展示年月日 -->
二维码有效期至 {{ fmtClock(signCode.expire_at) }}
<template v-if="signCode.geo_radius"> · 定位半径 {{ signCode.geo_radius }}m</template> <template v-if="signCode.geo_radius"> · 定位半径 {{ signCode.geo_radius }}m</template>
</div> </div>
<!-- 二维码地址预检:非对外域名生成时当场提醒,避免学员扫码后企微报
"redirect_uri需使用应用可信域名"(2026-11 联调反馈) -->
<div class="sign-code-box__countdown is-stale" v-if="signCode && qrOriginWarn">
当前页面地址({{ qrOriginHost }})不是对外域名,学员扫码无法签到 —— 请从 kbt/kb.well-trust.com 打开本页重新生成
</div>
<!-- 自动轮换倒计时(2026-11 需求:二维码每 5 分钟自动更新,旧码即时作废; <!-- 自动轮换倒计时(2026-11 需求:二维码每 5 分钟自动更新,旧码即时作废;
轮换由后端在轮询读取时惰性触发,本页每 10s 轻量轮询驱动) --> 轮换由后端在轮询读取时惰性触发,本页每 10s 轻量轮询驱动) -->
<div class="sign-code-box__countdown" v-if="signCode && rotateRemainSec > 0"> <div class="sign-code-box__countdown" v-if="signCode && rotateRemainSec > 0">
@@ -105,13 +111,15 @@
<!-- 签到明细 --> <!-- 签到明细 -->
<div class="records-header"> <div class="records-header">
<span class="records-header__title">签到明细</span> <span class="records-header__title">签到明细</span>
<t-button v-if="canReview && signCode" variant="outline" size="small" @click="proxyVisible = true">代扫码 / 补录</t-button> <t-button v-if="canReview && signCode" variant="outline" size="small" @click="proxyVisible = true">补录</t-button>
</div> </div>
<t-table :data="records" :columns="recordColumns" row-key="id" size="small" :loading="loading"> <t-table :data="pagedRecords" :columns="recordColumns" row-key="id" size="small" :loading="loading">
<template #member="{ row }">{{ memberLabel(row.member_id) }}</template> <template #member="{ row }">{{ recordMemberLabel(row) }}</template>
<template #signed_at="{ row }">{{ fmtRecordTime(row.signed_at) }}</template>
<template #channel="{ row }">{{ channelText(row.channel) }}</template>
<template #status="{ row }"> <template #status="{ row }">
<t-tag :theme="statusTheme(row.status)" variant="light" size="small">{{ statusText(row.status) }}</t-tag> <t-tag :theme="statusTheme(row.status)" variant="light" size="small">{{ statusText(row.status) }}</t-tag>
<t-tag v-for="f in row.abnormal_flags || []" :key="f" theme="danger" variant="outline" size="small" class="flag-tag">{{ flagText(f) }}</t-tag> <t-tag v-for="f in extraFlags(row)" :key="f" theme="danger" variant="outline" size="small" class="flag-tag">{{ flagText(f) }}</t-tag>
</template> </template>
<template #op="{ row }"> <template #op="{ row }">
<template v-if="canReview && row.status !== 'normal'"> <template v-if="canReview && row.status !== 'normal'">
@@ -120,9 +128,11 @@
</template> </template>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="recordPage" v-model:page-size="recordPageSize" :total="recordTotal" />
<!-- 代扫码 / 补录:走同一防伪规则引擎,proxy 标记留痕 --> <!-- 补录:走同一防伪规则引擎,proxy 标记留痕 -->
<t-dialog v-model:visible="proxyVisible" header="代扫码 / 现场补录" width="460"> <t-dialog v-model:visible="proxyVisible" header="现场补录" width="460">
<t-form label-width="90"> <t-form label-width="90">
<t-form-item label="学员" required> <t-form-item label="学员" required>
<t-select v-model="proxyMemberId" filterable placeholder="选择要补录的学员" style="width: 100%"> <t-select v-model="proxyMemberId" filterable placeholder="选择要补录的学员" style="width: 100%">
@@ -193,7 +203,9 @@ import {
type TrainingSignRecord, type TrainingSignRecord,
unwrap, unwrap,
} from '@/api/training' } from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingClock, fmtBeijingTime, fmtBeijingTimeSec } from '@/utils/datetime'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
const props = defineProps<{ roles: string[]; admin?: boolean }>() const props = defineProps<{ roles: string[]; admin?: boolean }>()
const route = useRoute() const route = useRoute()
@@ -226,6 +238,15 @@ const signCode = ref<TrainingSignCode | null>(null)
const summary = ref<SignSummary | null>(null) const summary = ref<SignSummary | null>(null)
const records = ref<TrainingSignRecord[]>([]) const records = ref<TrainingSignRecord[]>([])
// 签到明细分页(000163):默认每页 15 条;切换场次后回到第 1 页
const {
page: recordPage,
pageSize: recordPageSize,
total: recordTotal,
paged: pagedRecords,
reset: resetRecordPage,
} = useTrainingPager(records)
const recordColumns = [ const recordColumns = [
{ colKey: 'member', title: '学员', width: 220 }, { colKey: 'member', title: '学员', width: 220 },
{ colKey: 'signed_at', title: '签到时间', width: 170 }, { colKey: 'signed_at', title: '签到时间', width: 170 },
@@ -243,6 +264,12 @@ const statusTheme = (s: string) => ({
normal: 'success', late: 'warning', abnormal: 'danger', outside: 'danger', duplicate: 'danger', missing: 'default', normal: 'success', late: 'warning', abnormal: 'danger', outside: 'danger', duplicate: 'danger', missing: 'default',
}[s] || 'default') }[s] || 'default')
// 签到明细列展示口径(000165):
// 签到时间 → 北京时间「YYYY/MM/DD HH:mm:ss」(带秒)
// 方式 → 中文(企微扫码/代扫码补录),未知值回退原文
const fmtRecordTime = (raw: string | null) => fmtBeijingTimeSec(raw) || '—'
const channelText = (c: string) => ({ wecom_scan: '企微扫码', proxy: '代扫码/补录' }[c] || c)
// 签到二维码:内容为学员扫码签到页链接(携带 token),本地生成不依赖外网服务; // 签到二维码:内容为学员扫码签到页链接(携带 token),本地生成不依赖外网服务;
// 签到码刷新/切换场次后自动重绘。 // 签到码刷新/切换场次后自动重绘。
const signQrUrl = ref('') const signQrUrl = ref('')
@@ -252,7 +279,7 @@ const buildSignQr = async () => {
signQrUrl.value = '' signQrUrl.value = ''
return return
} }
const url = `${window.location.origin}/platform/training/checkin/${token}` const url = `${window.location.origin}/m/training/checkin/${token}`
try { try {
signQrUrl.value = await QRCode.toDataURL(url, { width: 320, margin: 1 }) signQrUrl.value = await QRCode.toDataURL(url, { width: 320, margin: 1 })
} catch { } catch {
@@ -261,6 +288,22 @@ const buildSignQr = async () => {
} }
watch(signCode, buildSignQr, { immediate: true }) watch(signCode, buildSignQr, { immediate: true })
// 二维码地址预检:企微 OAuth 要求 redirect_uri 使用应用可信域名,二维码内容
// 取本页 origin —— 若讲师在本机/内网地址打开培训签到页,学员扫码必然失败。
// 启发式与后端 checkin-auth 预检同口径(localhost/内网 IP/单标签/伪域名)。
const qrOriginHost = window.location.hostname.toLowerCase()
const qrOriginWarn = (() => {
const h = qrOriginHost
if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || !h.includes('.')) return true
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(h)) {
const [a, b] = h.split('.').map(Number)
if (a === 127 || a === 10 || a === 192) return true
if (a === 172 && b >= 16 && b <= 31) return true
if (a === 169 && b === 254) return true
}
return /\.(local|lan|internal|localhost)$/.test(h)
})()
// ---- 签到码自动轮换(2026-11 企微扫码需求) ---- // ---- 签到码自动轮换(2026-11 企微扫码需求) ----
// 后端在 GET sign-code 超过轮换窗口(rotation_sec,默认 5 分钟)时惰性轮换: // 后端在 GET sign-code 超过轮换窗口(rotation_sec,默认 5 分钟)时惰性轮换:
// 旧 token 挪入 prev(30s 宽限后彻底作废),新码即时生效。本页每 10s 轻量轮询 // 旧 token 挪入 prev(30s 宽限后彻底作废),新码即时生效。本页每 10s 轻量轮询
@@ -319,6 +362,8 @@ const flagText = (f: string) => ({ late: '迟到', outside: '定位异常', not_
const courseName = (courseId: string) => courses.value.find((c) => c.id === courseId)?.name || '课程' const courseName = (courseId: string) => courses.value.find((c) => c.id === courseId)?.name || '课程'
const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '—' const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '—'
// 签到码有效期只展示时分(测试反馈 2026-11-26:去掉年月日)
const fmtClock = (raw: string | null) => fmtBeijingClock(raw) || '—'
const memberLabels = ref<Record<string, string>>({}) const memberLabels = ref<Record<string, string>>({})
const members = ref<TrainingMember[]>([]) const members = ref<TrainingMember[]>([])
@@ -326,12 +371,26 @@ const proxyVisible = ref(false)
const proxyMemberId = ref('') const proxyMemberId = ref('')
const proxyLoading = ref(false) const proxyLoading = ref(false)
// 学员展示口径(000165):「姓名 工号」;未入名册时回退 member_id 前缀
const memberLabel = (memberId: string) => memberLabels.value[memberId] || memberId const memberLabel = (memberId: string) => memberLabels.value[memberId] || memberId
const memberLabelText = (m: TrainingMember) => { const memberLabelText = (m: TrainingMember) =>
const role = (m.post || '').trim() [m.user_name || m.employee_no || '-', m.employee_no && m.user_name ? m.employee_no : '']
return `${m.employee_no || '-'} ${role ? ` · ${role}` : ''}` .filter(Boolean)
.join(' ')
// 签到明细学员列优先后端联查返回的「姓名 工号」(明细接口已 JOIN 员工档案,
// 不再依赖名册全量反查 —— 名册分页截断时曾回退显示 member_id);缺失时回退
// 名册标签,再回退 member_id 前缀。
const recordMemberLabel = (row: TrainingSignRecord) => {
const direct = [row.member_name || '', row.employee_no || ''].filter(Boolean).join(' ')
return direct || memberLabel(row.member_id)
} }
// 状态标签已表达 outside 时,abnormal_flags 里的同名标记不再重复渲染
// (复核前曾出现连续两个「定位异常」标签)。
const extraFlags = (row: TrainingSignRecord) =>
(row.abnormal_flags || []).filter((f) => !(f === 'outside' && row.status === 'outside'))
const loadAll = async () => { const loadAll = async () => {
loading.value = true loading.value = true
try { try {
@@ -346,10 +405,9 @@ const loadAll = async () => {
if (memberItems.length) { if (memberItems.length) {
members.value = memberItems members.value = memberItems
const labels: Record<string, string> = {} const labels: Record<string, string> = {}
const deptNames: Record<string, string> = {}
for (const mem of members.value) { for (const mem of members.value) {
labels[mem.id] = `${mem.employee_no || '-'} ${mem.post || ''}`.trim() || mem.id.slice(0, 8) // 签到明细学员列(000165):「姓名 工号」,无姓名时回退工号
if (mem.dept_id) deptNames[mem.dept_id] = deptNames[mem.dept_id] || '' labels[mem.id] = [mem.user_name || '', mem.employee_no || ''].filter(Boolean).join(' ') || mem.id.slice(0, 8)
} }
memberLabels.value = labels memberLabels.value = labels
} }
@@ -361,6 +419,7 @@ const loadAll = async () => {
const loadSessionData = async () => { const loadSessionData = async () => {
if (!selectedSessionId.value) return if (!selectedSessionId.value) return
const sid = selectedSessionId.value const sid = selectedSessionId.value
resetRecordPage()
try { try {
const [code, sum, recs, evs] = await Promise.all([ const [code, sum, recs, evs] = await Promise.all([
getSignCode(sid).catch(() => null), getSignCode(sid).catch(() => null),
@@ -22,7 +22,7 @@
<span class="panel-box__title">我的学习任务</span> <span class="panel-box__title">我的学习任务</span>
<span class="panel-box__sub">点击课程名进入学习,进度 ≥95% 自动完成</span> <span class="panel-box__sub">点击课程名进入学习,进度 ≥95% 自动完成</span>
</div> </div>
<t-table :data="tasks" :columns="taskColumns" row-key="id" size="small"> <t-table :data="pagedTasks" :columns="taskColumns" row-key="id" size="small">
<template #course_name="{ row }"> <template #course_name="{ row }">
<a class="task-course-link" @click="goCourse(row.course_id)">{{ row.course_name }}</a> <a class="task-course-link" @click="goCourse(row.course_id)">{{ row.course_name }}</a>
</template> </template>
@@ -31,6 +31,7 @@
<t-tag :theme="taskTheme(row.status)" variant="light" size="small">{{ taskText(row.status) }}</t-tag> <t-tag :theme="taskTheme(row.status)" variant="light" size="small">{{ taskText(row.status) }}</t-tag>
</template> </template>
</t-table> </t-table>
<TrainingPagination v-model:current="taskPage" v-model:page-size="taskPageSize" :total="taskTotal" />
<t-empty v-if="!tasks.length" description="暂无学习任务,课程发布后将自动生成" /> <t-empty v-if="!tasks.length" description="暂无学习任务,课程发布后将自动生成" />
</div> </div>
@@ -38,7 +39,7 @@
<div class="panel-box__header"> <div class="panel-box__header">
<span class="panel-box__title">我的考试成绩</span> <span class="panel-box__title">我的考试成绩</span>
</div> </div>
<t-table :data="myRecords" :columns="myRecordColumns" row-key="id" size="small" :loading="loading"> <t-table :data="pagedMyRecords" :columns="myRecordColumns" row-key="id" size="small" :loading="loading">
<template #course_name="{ row }">{{ row.course_name || row.paper_name || '-' }}</template> <template #course_name="{ row }">{{ row.course_name || row.paper_name || '-' }}</template>
<template #score="{ row }"> <template #score="{ row }">
<span :class="passClass(row)">{{ row.score ?? '—' }}</span> <span :class="passClass(row)">{{ row.score ?? '—' }}</span>
@@ -46,6 +47,7 @@
<template #pass_line="{ row }">{{ row.pass_score || '-' }} / {{ row.total_score || '-' }}</template> <template #pass_line="{ row }">{{ row.pass_score || '-' }} / {{ row.total_score || '-' }}</template>
<template #submitted_at="{ row }">{{ fmtTime(row.submitted_at) }}</template> <template #submitted_at="{ row }">{{ fmtTime(row.submitted_at) }}</template>
</t-table> </t-table>
<TrainingPagination v-model:current="myRecordPage" v-model:page-size="myRecordPageSize" :total="myRecordTotal" />
<t-empty v-if="!myRecords.length" description="暂无考试记录,参加随堂考试后此处展示成绩" /> <t-empty v-if="!myRecords.length" description="暂无考试记录,参加随堂考试后此处展示成绩" />
</div> </div>
@@ -53,7 +55,7 @@
<div class="panel-box__header"> <div class="panel-box__header">
<span class="panel-box__title">我的错题本</span> <span class="panel-box__title">我的错题本</span>
</div> </div>
<t-table :data="wrongBook" :columns="wrongColumns" row-key="id" size="small"> <t-table :data="pagedWrongBook" :columns="wrongColumns" row-key="id" size="small">
<template #knowledge_point="{ row }"> <template #knowledge_point="{ row }">
<t-tag v-if="row.knowledge_point" variant="light" size="small">{{ row.knowledge_point }}</t-tag> <t-tag v-if="row.knowledge_point" variant="light" size="small">{{ row.knowledge_point }}</t-tag>
<span v-else>—</span> <span v-else>—</span>
@@ -64,6 +66,7 @@
</t-tag> </t-tag>
</template> </template>
</t-table> </t-table>
<TrainingPagination v-model:current="wrongPage" v-model:page-size="wrongPageSize" :total="wrongTotal" />
<t-empty v-if="!wrongBook.length" description="错题本为空,继续保持" /> <t-empty v-if="!wrongBook.length" description="错题本为空,继续保持" />
</div> </div>
@@ -144,6 +147,8 @@ import { fmtBeijingTime } from '@/utils/datetime'
import CourseLearningStatus from './CourseLearningStatus.vue' import CourseLearningStatus from './CourseLearningStatus.vue'
import ExamPanel from './ExamPanel.vue' import ExamPanel from './ExamPanel.vue'
import CourseAIAnalysis from './CourseAIAnalysis.vue' import CourseAIAnalysis from './CourseAIAnalysis.vue'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
const props = defineProps<{ roles: string[]; admin?: boolean }>() const props = defineProps<{ roles: string[]; admin?: boolean }>()
// 课程学习/考试情况管理端:人事/课长/讲师(roles 已按权限组展开,经理自动命中) // 课程学习/考试情况管理端:人事/课长/讲师(roles 已按权限组展开,经理自动命中)
@@ -228,6 +233,11 @@ const taskText = (s: string) => ({ pending: '待学习', doing: '学习中', don
const taskTheme = (s: string) => ({ pending: 'default', doing: 'primary', done: 'success', overdue: 'danger' }[s] || 'default') const taskTheme = (s: string) => ({ pending: 'default', doing: 'primary', done: 'success', overdue: 'danger' }[s] || 'default')
const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '—' const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '—'
// 四宫格列表分页(000163):学习任务/考试成绩/错题本默认每页 15 条
const { page: taskPage, pageSize: taskPageSize, total: taskTotal, paged: pagedTasks } = useTrainingPager(tasks)
const { page: myRecordPage, pageSize: myRecordPageSize, total: myRecordTotal, paged: pagedMyRecords } = useTrainingPager(myRecords)
const { page: wrongPage, pageSize: wrongPageSize, total: wrongTotal, paged: pagedWrongBook } = useTrainingPager(wrongBook)
const passClass = (row: MyExamRecord) => { const passClass = (row: MyExamRecord) => {
if (row.score == null) return '' if (row.score == null) return ''
return row.pass_score ? (row.score >= row.pass_score ? 'tone-good' : 'tone-bad') : '' return row.pass_score ? (row.score >= row.pass_score ? 'tone-good' : 'tone-bad') : ''
@@ -0,0 +1,50 @@
<template>
<!-- 企业培训共用分页条:所有列表页统一挂载,默认每页 15 条 -->
<div v-if="total > 0" class="training-pagination">
<span class="training-pagination__total">共 {{ total }} 条</span>
<t-pagination
v-model="current"
v-model:page-size="pageSize"
:total="total"
size="small"
:show-jumper="false"
show-page-number
:show-page-size="total > TRAINING_PAGE_SIZE"
:page-size-options="TRAINING_PAGE_SIZE_OPTIONS"
:disabled="disabled"
/>
</div>
</template>
<script setup lang="ts">
import { TRAINING_PAGE_SIZE, TRAINING_PAGE_SIZE_OPTIONS } from './useTrainingPager'
// 共用分页组件(000163):企业培训各列表页统一口径 —— 默认每页 15 条,
// 页码/每页条数由父组件经 useTrainingPager 提供并做客户端切片。
withDefaults(
defineProps<{
total: number
disabled?: boolean
}>(),
{ disabled: false },
)
const current = defineModel<number>('current', { default: 1 })
const pageSize = defineModel<number>('pageSize', { default: TRAINING_PAGE_SIZE })
</script>
<style lang="less" scoped>
.training-pagination {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 12px;
margin-top: 12px;
&__total {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
white-space: nowrap;
}
}
</style>
@@ -0,0 +1,45 @@
import { computed, ref, watch, type Ref } from 'vue'
// 企业培训共用分页口径(000163):默认每页 15 条
export const TRAINING_PAGE_SIZE = 15
export const TRAINING_PAGE_SIZE_OPTIONS = [15, 30, 50, 100]
/**
* 企业培训列表共用客户端分页(000163):
* 列表页均为全量加载 + 本地过滤,分页在前端切片完成。
* 传入过滤后的全量列表,返回当前页切片与分页状态(供 TrainingPagination 绑定);
* 列表条数变化时自动夹紧页码,reset() 供「重置」按钮回到第 1 页。
*/
export function useTrainingPager<T>(source: Ref<T[]> | (() => T[])) {
const page = ref(1)
const pageSize = ref(TRAINING_PAGE_SIZE)
const list = computed<T[]>(() => (typeof source === 'function' ? source() : source.value))
const total = computed(() => list.value.length)
const paged = computed<T[]>(() => {
const start = (page.value - 1) * pageSize.value
return list.value.slice(start, start + pageSize.value)
})
// 条数/每页条数变化后夹紧页码(过滤收紧或翻页超界时不出现空页)
watch([total, pageSize], () => {
const maxPage = Math.max(1, Math.ceil(total.value / pageSize.value))
if (page.value > maxPage) page.value = maxPage
})
const reset = () => {
page.value = 1
}
return { page, pageSize, total, paged, reset }
}
/**
* 计划培训时间排序键(000163):「2027-1」「2027-11」「2027-03-15 14:00」等
* 统一解析为「年×12+月」序号,供列表按计划培训时间倒序排列(字符串直排会把
* 2027-2 排到 2027-12 之后);无法解析返回 -1(无计划培训时间的行排最后)。
*/
export function plannedMonthSortKey(value?: string | null): number {
const m = (value || '').trim().match(/^(\d{4})-(\d{1,2})/)
return m ? Number(m[1]) * 12 + Number(m[2]) : -1
}
+53
View File
@@ -124,6 +124,45 @@
} }
} }
// 列表页满屏布局(年培训计划/月培训计划/课程管理):页头(标题)固定不动,
// 面板占满页身剩余高度,内部「面板标题/筛选区/分页」固定,仅表格数据区滚动。
// 约定:panel-box 收为 flex 列,表格外包一层 .table-scroll(flex:1 撑满剩余
// 高度),表格传 height="100%" 启用 TDesign 固定表头(thead sticky + 数据行滚动)。
.training-fill-panel() {
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
> .panel-box {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
> .panel-box > .panel-box__header,
> .panel-box > .panel-box__sub {
flex-shrink: 0;
}
> .panel-box > .table-scroll {
flex: 1;
min-height: 0;
// 满屏关键:TDesign 的 height="100%" 落在内部 .t-table__content 上,而其父级
// .t-table 根默认 auto 高,百分比会退化为内容高(表头固定不生效);给根也撑满
// 100% 形成确定高度链,数据区才会真正滚动
> .t-table {
height: 100%;
}
}
> .panel-box > .training-pagination {
flex-shrink: 0;
}
}
// 内容卡片:对齐知识库 resource-card 规范(描边 + 8px 圆角 + 容器底色) // 内容卡片:对齐知识库 resource-card 规范(描边 + 8px 圆角 + 容器底色)
.training-panel-box() { .training-panel-box() {
background: var(--td-bg-color-container); background: var(--td-bg-color-container);
@@ -171,6 +210,20 @@
margin-bottom: 16px; margin-bottom: 16px;
} }
// 表单项内提示文案统一另起一行(000163):t-form__controls-content 为 flex 行排布,
// 控件后的提示块(bank-hint/form-hint)会被排到控件右侧,此处强制换行占满整行,
// 统一展示在控件下方
.training-form-hints-below() {
:deep(.t-form__controls-content) {
flex-wrap: wrap;
}
:deep(.t-form__controls-content .bank-hint),
:deep(.t-form__controls-content .form-hint) {
flex-basis: 100%;
}
}
.training-stat-card() { .training-stat-card() {
background: var(--td-bg-color-secondarycontainer); background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-md); border-radius: var(--app-radius-md);
@@ -13,7 +13,8 @@
* 「题库与考试 → Excel 批量导入」与「培训课程 → 创建课程 → 关联题库」指引使用; * 「题库与考试 → Excel 批量导入」与「培训课程 → 创建课程 → 关联题库」指引使用;
* 工作表:单选题/多选题/判断题,列:题目/课程名称/难度/正确答案/答案A..答案L。 * 工作表:单选题/多选题/判断题,列:题目/课程名称/难度/正确答案/答案A..答案L。
* - course_library 课程管理导入模板.xlsx:「课程管理 → 批量导入」使用; * - course_library 课程管理导入模板.xlsx:「课程管理 → 批量导入」使用;
* 列:课程名称/说明/分类/类型/线上,线下/讲师/时长(学时)/课件。 * 000165 复测列序:所属部门/课程名称/讲师/课程权限/课程分类/类型/线上或线下/
* 时长(学时)/课程说明/适合人员备注(无课件收集列,课件经列表「课件」入口维护)。
*/ */
import { downloadTrainingTemplateFile, type TrainingTemplateKey } from '@/api/training' import { downloadTrainingTemplateFile, type TrainingTemplateKey } from '@/api/training'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
@@ -0,0 +1,34 @@
package repository
import (
"strings"
"testing"
"academy/internal/types/interfaces"
)
// TestCourseLibraryPermissionCondBalanced 2026-11-26 复测根因:权限 SQL 括号不配平
// (少一个右括号)导致 scope=catalog / PermFilter 查询整体 500
// 「syntax error at end of input」,前端 catch 后和信课程恒为空。
// 本测试锁定:生成 SQL 括号必须配平,占位符数量与参数数量必须一致。
func TestCourseLibraryPermissionCondBalanced(t *testing.T) {
q := &interfaces.TrainingListQuery{
PermFilter: true,
PermDeptID: "dept-1",
PermUserID: "user-1",
CatalogDeptID: "dept-1",
CatalogDeptName: "资讯组",
PermIncludeCreator: true,
}
cond, args := courseLibraryPermissionCond(q)
opens := strings.Count(cond, "(")
closes := strings.Count(cond, ")")
if opens != closes {
t.Fatalf("括号不配平: '('=%d ')'=%d\nSQL=%s", opens, closes, cond)
}
placeholders := strings.Count(cond, "?")
if placeholders != len(args) {
t.Fatalf("占位符(%d)与参数(%d)数量不一致\nSQL=%s", placeholders, len(args), cond)
}
t.Logf("OK opens=%d closes=%d placeholders=%d args=%d", opens, closes, placeholders, len(args))
}
@@ -59,6 +59,19 @@ func (r *trainingRepository) GetMemberByWecomUserid(ctx context.Context, tenantI
return &m, nil return &m, nil
} }
// GetMemberByEmployeeNo 工号扫码签到反查(2026-11-25 调整):按工号定位培训
// 档案。同工号多行(历史重复导入)取最早建档行,保证同一工号稳定映射同一人。
func (r *trainingRepository) GetMemberByEmployeeNo(ctx context.Context, tenantID uint64, employeeNo string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND employee_no = ?", tenantID, employeeNo).
Order("created_at ASC").
First(&m).Error; err != nil {
return nil, err
}
return &m, nil
}
// FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160): // FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160):
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、 // 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户, // 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
@@ -641,7 +641,7 @@ func (r *trainingRepository) EvidenceRows(ctx context.Context, tenantID uint64,
Table("tr_sign_records sr"). Table("tr_sign_records sr").
Select(`COALESCE(dp.name, '') AS dept_name, Select(`COALESCE(dp.name, '') AS dept_name,
COALESCE(m.employee_no, '') AS employee_no, COALESCE(m.employee_no, '') AS employee_no,
COALESCE(u.username, '') AS member_name, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS member_name,
TO_CHAR(sr.signed_at, 'YYYY-MM-DD HH24:MI') AS signed_at, TO_CHAR(sr.signed_at, 'YYYY-MM-DD HH24:MI') AS signed_at,
COALESCE(lu.username, '') AS lecturer_name, COALESCE(lu.username, '') AS lecturer_name,
COALESCE(c.name, '') AS course_name, COALESCE(c.name, '') AS course_name,
@@ -13,6 +13,43 @@ import (
// 月培训计划的「计划名称」从本表选择,选中后经 tr_courses.library_course_id 关联。 // 月培训计划的「计划名称」从本表选择,选中后经 tr_courses.library_course_id 关联。
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// courseLibraryPermissionMatchSQL 课程权限覆盖判定(000163):
// - perm_dept_ids 含调用方部门 id → 可见;或调用方部门名与 perm 列表中某部门
// (org_depts 按 id 反查)同名 → 可见(2026-11-26 复测加固:个别环境员工
// 档案 dept_id 与部门选择器落库的 id 口径不一致时,同部门仍按名命中);
// - perm_user_ids 含调用方用户 id → 可见;
// - perm 两列为空的存量课程沿用 suitable_members 老口径:'全部' 全员可见 /
// 部门名成员匹配(逗号/分号归一为「、」)/ 所属部门兜底(空=全员)。
//
// 参数顺序:PermDeptID×2, CatalogDeptName×2, PermUserID×2,
// '全部', CatalogDeptName×2, CatalogDeptID×2。
const courseLibraryPermissionMatchSQL = "(tr_course_library.perm_dept_ids <> '' AND ((? <> '' AND ? = ANY(string_to_array(tr_course_library.perm_dept_ids, ','))) " +
"OR (? <> '' AND EXISTS (SELECT 1 FROM org_depts pd WHERE pd.tenant_id = tr_course_library.tenant_id AND pd.deleted_at IS NULL " +
"AND pd.name = ? AND pd.id = ANY(string_to_array(tr_course_library.perm_dept_ids, ',')))))) " +
"OR (tr_course_library.perm_user_ids <> '' AND ? <> '' AND ? = ANY(string_to_array(tr_course_library.perm_user_ids, ','))) " +
"OR (tr_course_library.perm_dept_ids = '' AND tr_course_library.perm_user_ids = '' AND (" +
"tr_course_library.suitable_members = ? " +
"OR (? <> '' AND ? = ANY(string_to_array(replace(replace(replace(replace(tr_course_library.suitable_members, ',', '、'), ',', '、'), ';', '、'), ';', '、'), '、'))) " +
"OR (tr_course_library.suitable_members = '' AND (tr_course_library.owner_dept_id = '' " +
"OR (? <> '' AND tr_course_library.owner_dept_id = ?)))))"
// courseLibraryPermissionCond 组装课程权限匹配条件与参数(000163;handler 注入
// 调用方部门 id/部门名/用户 id,PermIncludeCreator 时创建人/讲师放行)。
func courseLibraryPermissionCond(q *interfaces.TrainingListQuery) (string, []interface{}) {
cond := courseLibraryPermissionMatchSQL
args := []interface{}{
q.PermDeptID, q.PermDeptID,
q.CatalogDeptName, q.CatalogDeptName,
q.PermUserID, q.PermUserID,
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID,
}
if q.PermIncludeCreator {
cond += " OR (tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?)"
args = append(args, q.PermUserID, q.PermUserID)
}
return "(" + cond + ")", args
}
// ListCourseLibrary returns a page of course-library items with keyword filter // 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) { func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
@@ -31,20 +68,23 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
if q.RelatedUserID != "" { if q.RelatedUserID != "" {
tx = tx.Where("tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?", q.RelatedUserID, q.RelatedUserID) tx = tx.Where("tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?", q.RelatedUserID, q.RelatedUserID)
} }
// 学员目录口径(000160,scope=catalog):仅已发布 + 适合人员覆盖调用方。 // 学员目录口径(000160,scope=catalog):仅已发布 + 课程权限覆盖调用方
// suitable='全部' 全员可见;000159 多部门口径:值按「、」拆分(逗号/分号 // (000163:perm 两列精确命中;存量课程沿用 suitable_members 老口径)。
// 兼容归一)后与调用方部门名做成员匹配;未设置适合人员的存量课程沿用
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。调用方
// 无部门档案时只见「全部」与未设置的课程。
if q.CatalogOnly { if q.CatalogOnly {
tx = tx.Where("tr_course_library.publish_status = ?", "published") tx = tx.Where("tr_course_library.publish_status = ?", "published")
tx = tx.Where( cond, args := courseLibraryPermissionCond(q)
"tr_course_library.suitable_members = ? "+ tx = tx.Where(cond, args...)
"OR (? <> '' AND ? = ANY(string_to_array(replace(replace(replace(replace(tr_course_library.suitable_members, ',', '、'), ',', '、'), ';', '、'), ';', '、'), '、'))) "+ }
"OR (tr_course_library.suitable_members = '' AND (tr_course_library.owner_dept_id = '' "+ // 课程权限过滤(000163):计划选课/无维护角色视图按调用方部门+人员收窄
"OR (? <> '' AND tr_course_library.owner_dept_id = ?)))", // (与 catalog 同一匹配口径,handler 按视图注入调用方身份与放行项)。
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID, if q.PermFilter {
) cond, args := courseLibraryPermissionCond(q)
tx = tx.Where(cond, args...)
}
// 计划选课口径(000163,scope=plan):已下线课程不再可选(存量计划行
// tr_courses 不受影响,历史计划照常展示)。
if q.ExcludeOffline {
tx = tx.Where("tr_course_library.publish_status <> ?", "offline")
} }
} }
var total int64 var total int64
@@ -103,6 +143,26 @@ func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID
return &item, nil return &item, nil
} }
// ListCourseLibraryStatuses 批量取课程管理条目的发布状态(000163:月培训计划
// 列表/学习页据此拦截「该课程已下线」;ids 为 tr_courses.library_course_id 集合)。
func (r *trainingRepository) ListCourseLibraryStatuses(ctx context.Context, tenantID uint64, ids []string) (map[string]string, error) {
out := make(map[string]string, len(ids))
if len(ids) == 0 {
return out, nil
}
var rows []*types.TrainingCourseLibrary
if err := r.db.WithContext(ctx).
Select("id, publish_status").
Where("tenant_id = ? AND id IN ?", tenantID, ids).
Find(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
out[row.ID] = row.PublishStatus
}
return out, nil
}
// CreateCourseLibraryItem inserts one course-library item. // CreateCourseLibraryItem inserts one course-library item.
func (r *trainingRepository) CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error { func (r *trainingRepository) CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error {
return r.db.WithContext(ctx).Create(item).Error return r.db.WithContext(ctx).Create(item).Error
@@ -118,6 +178,11 @@ func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *
"owner_dept_id": item.OwnerDeptID, "owner_dept_id": item.OwnerDeptID,
"description": item.Description, "description": item.Description,
"suitable_members": item.SuitableMembers, "suitable_members": item.SuitableMembers,
// 课程权限(000163):部门/人员 id 列表随保存更新。
"perm_dept_ids": item.PermDeptIDs,
"perm_user_ids": item.PermUserIDs,
// 适合人员备注(000165):随保存更新(空值即清空)。
"post_scope": item.PostScope,
"category": item.Category, "category": item.Category,
"type": item.Type, "type": item.Type,
"mode": item.Mode, "mode": item.Mode,
@@ -130,6 +195,8 @@ func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *
"file_size": item.FileSize, "file_size": item.FileSize,
// 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。 // 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。
"knowledge_id": item.KnowledgeID, "knowledge_id": item.KnowledgeID,
// 课件列表(000164 多课件,JSON 数组;主字段镜像最新条)。
"materials": item.Materials,
// 核验状态(000157):编辑/换课件后由服务层重置为待核验并清空核验痕迹。 // 核验状态(000157):编辑/换课件后由服务层重置为待核验并清空核验痕迹。
"verify_status": item.VerifyStatus, "verify_status": item.VerifyStatus,
"confirmed_by": item.ConfirmedBy, "confirmed_by": item.ConfirmedBy,
@@ -2,6 +2,7 @@ package repository
import ( import (
"context" "context"
"strings"
"time" "time"
"academy/internal/types" "academy/internal/types"
@@ -442,9 +443,39 @@ func (r *trainingRepository) ListSessions(ctx context.Context, tenantID uint64,
return items, err return items, err
} }
// FirstCourseSession 取课程最靠前的有效场次(2026-11-26 复测:发布校验的授课
// 时间/地点与列表展示同口径 —— 场次排期优先;存量计划课程级字段为空但场次已
// 排期时不误报「未设置」)。优先排期中且带时间/地点的场次,其次任一带时间或
// 地点的场次,最后回退第一场;无场次返回 nil。
func (r *trainingRepository) FirstCourseSession(ctx context.Context, tenantID uint64, courseID string) (*types.TrainingCourseSession, error) {
var items []*types.TrainingCourseSession
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND course_id = ?", tenantID, courseID).
Order("start_at ASC NULLS LAST").
Find(&items).Error; err != nil {
return nil, err
}
if len(items) == 0 {
return nil, nil
}
usable := func(s *types.TrainingCourseSession) bool {
return (s.StartAt != nil && !s.StartAt.IsZero()) || strings.TrimSpace(s.Location) != ""
}
for _, s := range items {
if s.Status == "scheduled" && usable(s) {
return s, nil
}
}
for _, s := range items {
if usable(s) {
return s, nil
}
}
return items[0], nil
}
// GetSession fetches one course session. // GetSession fetches one course session.
func (r *trainingRepository) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) { func (r *trainingRepository) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) { var s types.TrainingCourseSession
var s types.TrainingCourseSession
if err := r.db.WithContext(ctx). if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).First(&s).Error; err != nil { Where("tenant_id = ? AND id = ?", tenantID, id).First(&s).Error; err != nil {
return nil, err return nil, err
@@ -848,11 +879,21 @@ func (r *trainingRepository) GetSignRecordByID(ctx context.Context, tenantID uin
} }
// ListSignRecords returns all records of a session, earliest first. // ListSignRecords returns all records of a session, earliest first.
// 联查员工档案/账号/部门补齐学员展示字段(姓名/工号/部门):签到明细学员列
// 不能依赖前端名册全量反查(名册分页截断或未入名册时曾回退显示 member_id)。
func (r *trainingRepository) ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error) { func (r *trainingRepository) ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error) {
var items []*types.TrainingSignRecord var items []*types.TrainingSignRecord
err := r.db.WithContext(ctx). err := r.db.WithContext(ctx).
Where("tenant_id = ? AND session_id = ?", tenantID, sessionID). Table("tr_sign_records sr").
Order("signed_at ASC").Find(&items).Error Joins("LEFT JOIN org_employees e ON e.tenant_id = sr.tenant_id AND e.id = sr.member_id AND e.deleted_at IS NULL").
Joins("LEFT JOIN users u ON u.id = e.user_id").
Joins("LEFT JOIN org_depts dp ON dp.id = e.dept_id AND dp.tenant_id = e.tenant_id AND dp.deleted_at IS NULL").
Where("sr.tenant_id = ? AND sr.session_id = ? AND sr.deleted_at IS NULL", tenantID, sessionID).
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
// username 存工号,真实姓名在 display_name(与组织中心列表口径一致)。
Select(`sr.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS member_name,
COALESCE(e.employee_no, '') AS employee_no, COALESCE(dp.name, '') AS dept_name`).
Order("sr.signed_at ASC").Scan(&items).Error
return items, err return items, err
} }
+8 -3
View File
@@ -457,6 +457,8 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
OwnerDeptID: demand.DeptID, OwnerDeptID: demand.DeptID,
Category: demand.Category, Category: demand.Category,
SuitableMembers: demand.PostScope, SuitableMembers: demand.PostScope,
// 适合人员备注(000165):需求「适合人员」同步落到课程管理备注字段。
PostScope: demand.PostScope,
LecturerID: demand.LecturerID, LecturerID: demand.LecturerID,
LecturerExternal: demand.LecturerExternal, LecturerExternal: demand.LecturerExternal,
} }
@@ -538,6 +540,8 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
OwnerDeptID: demands[i].DeptID, OwnerDeptID: demands[i].DeptID,
Category: demands[i].Category, Category: demands[i].Category,
SuitableMembers: demands[i].PostScope, SuitableMembers: demands[i].PostScope,
// 适合人员备注(000165):批量导入同样同步到课程管理备注字段。
PostScope: demands[i].PostScope,
LecturerID: demands[i].LecturerID, LecturerID: demands[i].LecturerID,
LecturerExternal: demands[i].LecturerExternal, LecturerExternal: demands[i].LecturerExternal,
} }
@@ -599,13 +603,14 @@ func (s *trainingService) ConfirmDemand(ctx context.Context, tenantID uint64, id
} }
// DeleteDemand soft-deletes one unconfirmed demand. // DeleteDemand soft-deletes one unconfirmed demand.
// 状态「已确认」的需求不可删除,避免误删已纳入年度排期的口径。 // 状态「已确认」的需求不可删除,避免误删已纳入年度排期的口径;仅超级管理员
func (s *trainingService) DeleteDemand(ctx context.Context, tenantID uint64, id string) error { // (bySuperAdmin:super_admin 职称角色或空间 Owner 兜底)放开终态删除。
func (s *trainingService) DeleteDemand(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error {
demand, err := s.repo.GetDemand(ctx, tenantID, id) demand, err := s.repo.GetDemand(ctx, tenantID, id)
if err != nil { if err != nil {
return errors.NewNotFoundError("需求不存在") return errors.NewNotFoundError("需求不存在")
} }
if demand.Status == types.TrainingDemandConfirmed { if demand.Status == types.TrainingDemandConfirmed && !bySuperAdmin {
return errors.NewBadRequestError("已确认的需求不可删除") return errors.NewBadRequestError("已确认的需求不可删除")
} }
return s.repo.DeleteDemand(ctx, tenantID, id) return s.repo.DeleteDemand(ctx, tenantID, id)
@@ -57,9 +57,42 @@ func (s *trainingService) ListCourses(ctx context.Context, tenantID uint64, q *i
c.ExamStatus = courseExamStatus(c.ExpectedCount, st) c.ExamStatus = courseExamStatus(c.ExpectedCount, st)
} }
} }
// 关联课程管理条目的发布状态(000163):月培训计划列表标注「课程已下线」。
s.attachLibraryOffline(ctx, tenantID, courses...)
return courses, total, nil return courses, total, nil
} }
// attachLibraryOffline 批量回填课程关联课程管理条目的发布状态(000163):
// library_course_id 命中的条目已下线(publish_status=offline)时置
// LibraryOffline,学习入口按「该课程已下线」拦截(存量计划行保留不消失)。
// fail-open:查询失败保持零值,不阻断列表/详情。
func (s *trainingService) attachLibraryOffline(ctx context.Context, tenantID uint64, courses ...*types.TrainingCourse) {
ids := make([]string, 0, len(courses))
hit := make(map[string]bool, len(courses))
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" || hit[c.LibraryCourseID] {
continue
}
hit[c.LibraryCourseID] = true
ids = append(ids, c.LibraryCourseID)
}
if len(ids) == 0 {
return
}
statuses, err := s.repo.ListCourseLibraryStatuses(ctx, tenantID, ids)
if err != nil {
logger.Warnf(ctx, "Skip attach library offline status, tenant=%d error: %v", tenantID, err)
return
}
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" {
continue
}
c.LibraryPublishStatus = statuses[c.LibraryCourseID]
c.LibraryOffline = c.LibraryPublishStatus == "offline"
}
}
// courseLearnStatus 课程学习状态: // courseLearnStatus 课程学习状态:
// 无人签到且无人开始学习 → 未学习;完成人数(签到∪任务done)达到 // 无人签到且无人开始学习 → 未学习;完成人数(签到∪任务done)达到
// max(应到, 参与) → 已学习;否则 → 学习中。线下课签到即视同完成学习。 // max(应到, 参与) → 已学习;否则 → 学习中。线下课签到即视同完成学习。
@@ -126,6 +159,9 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil { if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil {
course.ExamReady = true course.ExamReady = true
} }
// 关联课程管理条目已下线时带出标记(000163):学习页据此提示
// 「该课程已下线」并拦截课件/考试入口。
s.attachLibraryOffline(ctx, tenantID, course)
return course, nil return course, nil
} }
@@ -161,7 +197,13 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
course.Hours = item.Hours course.Hours = item.Hours
} }
if course.Code == "" { if course.Code == "" {
course.Code = item.Code // 000163 根因修复:编号按租户流水独立生成,不再复制课程管理条目编号。
// tr_courses 有 (tenant_id, code) 唯一索引,复制 CRS-#### 后同一门课程
// 管理课程创建第二个月度计划必然撞唯一约束(500 duplicate key,
// 2026-11-25 测试环境「暂存草稿」即因此失败);计划行经 library_course_id
// 关联主数据,编号独立生成不影响带出与锁定逻辑。
// fail-open:计数器失败留空(唯一索引豁免空编号),不阻断保存。
course.Code = s.nextCourseLibraryCode(ctx, tenantID)
} }
if len(course.DeptIDs) == 0 || string(course.DeptIDs) == "[]" || string(course.DeptIDs) == "null" { if len(course.DeptIDs) == 0 || string(course.DeptIDs) == "[]" || string(course.DeptIDs) == "null" {
if item.OwnerDeptID != "" { if item.OwnerDeptID != "" {
@@ -380,7 +422,16 @@ func courseTypeLabel(t string) string {
} }
// DeleteCourse soft-deletes one course. // DeleteCourse soft-deletes one course.
func (s *trainingService) DeleteCourse(ctx context.Context, tenantID uint64, id string) error { // 已发布计划不可普通删除(避免误删已排期/已通知的计划);仅超级管理员
// (bySuperAdmin:super_admin 职称角色或空间 Owner 兜底)放开终态删除。
func (s *trainingService) DeleteCourse(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error {
course, err := s.GetCourse(ctx, tenantID, id)
if err != nil {
return err
}
if course.Status == types.TrainingCoursePublished && !bySuperAdmin {
return errors.NewBadRequestError("已发布的培训计划不可删除,仅超级管理员可删除")
}
return s.repo.DeleteCourse(ctx, tenantID, id) return s.repo.DeleteCourse(ctx, tenantID, id)
} }
@@ -434,6 +485,20 @@ func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id
} }
} }
if course.Mode != types.TrainingCourseModeOnline { if course.Mode != types.TrainingCourseModeOnline {
// 授课时间/地点与列表展示同口径(场次排期优先,2026-11-26 复测修复):
// 列表「授课时间/地点」列在课程级字段为空时展示场次排期值,校验若只读
// 课程级字段会把「场次已排期的存量草稿」误报为未设置 —— 课程级字段为空
// 时以最靠前的有效场次兜底(仅用于校验,不回写)。
if strings.TrimSpace(course.TeachTime) == "" || strings.TrimSpace(course.Location) == "" {
if session, sessErr := s.repo.FirstCourseSession(ctx, tenantID, course.ID); sessErr == nil && session != nil {
if strings.TrimSpace(course.TeachTime) == "" && session.StartAt != nil {
course.TeachTime = session.StartAt.Format("2006-01-02 15:04")
}
if strings.TrimSpace(course.Location) == "" {
course.Location = session.Location
}
}
}
if strings.TrimSpace(course.TeachTime) == "" { if strings.TrimSpace(course.TeachTime) == "" {
return nil, errors.NewBadRequestError("发布前需先设置授课时间") return nil, errors.NewBadRequestError("发布前需先设置授课时间")
} }
@@ -718,7 +783,12 @@ func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, s
if err != nil { if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在") return nil, errors.NewNotFoundError("课程场次不存在")
} }
if radius <= 0 { // 半径兜底仅在真实圆心下生效:前端生成签到码不携带定位(圆心为零值)时
// 不启用围栏 —— 否则 (0,0)+300m 会把所有真实扫码判成定位异常(距离一万
// 公里级)。需要围栏时由生成方显式传 geo_lat/geo_lng。
if lat == 0 && lng == 0 {
radius = 0
} else if radius <= 0 {
radius = int(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "geo_radius_m", 300)) radius = int(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "geo_radius_m", 300))
} }
now := time.Now() now := time.Now()
@@ -917,9 +987,10 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID s
status = types.TrainingSignLate status = types.TrainingSignLate
} }
// 定位围栏判定。 // 定位围栏判定。圆心 (0,0) 视为未配置(生成签到码不带定位时圆心落零值):
// 距离按 0 记、不打 outside —— 否则圆心在几万公里外,全国任意扫码全是定位异常。
distance := 0.0 distance := 0.0
if code.GeoRadius > 0 { if code.GeoRadius > 0 && (code.GeoLat != 0 || code.GeoLng != 0) {
distance = haversineMeters(lat, lng, code.GeoLat, code.GeoLng) distance = haversineMeters(lat, lng, code.GeoLat, code.GeoLng)
if distance > float64(code.GeoRadius) { if distance > float64(code.GeoRadius) {
flags = append(flags, "outside") flags = append(flags, "outside")
@@ -175,7 +175,14 @@ func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, t
libraryCourseID = oldLibraryCourseID libraryCourseID = oldLibraryCourseID
} }
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID} bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID}
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID) created, err := s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
if err != nil {
return nil, err
}
// 试题变更不再回待审核(000165 复测):课件/试题调整视为培训资料更新,
// 课程信息未变则维持原审核结论,月计划可直接发布;导入的题库即作为
// 本次培训试题(考试/学习均取该课程当前挂接题库)。
return created, nil
} }
// ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。 // ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。
@@ -188,6 +195,7 @@ func (s *trainingService) ListLibraryCourseQuestionBanks(ctx context.Context, te
// LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体 // LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体
// 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。 // 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。
// 更换试题不回待审核(000165 复测):维持原审核结论,月计划可直接发布。
func (s *trainingService) LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error { func (s *trainingService) LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error {
if libraryCourseID == "" { if libraryCourseID == "" {
return errors.NewBadRequestError("缺少课程管理条目") return errors.NewBadRequestError("缺少课程管理条目")
+2 -2
View File
@@ -222,8 +222,8 @@ func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64,
material, err := s.repo.GetMaterial(ctx, tenantID, materialID) material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
if err != nil { if err != nil {
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件): // 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
// 材料行不存在时按课程管理条目取文件流,与发布/学习链路同口径。 // 材料行不存在时按课程管理条目取文件流(最新课件条目),与发布/学习链路同口径。
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID); libErr == nil { if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID, ""); libErr == nil {
return rc, fileName, nil return rc, fileName, nil
} }
return nil, "", werrors.NewNotFoundError("课件不存在") return nil, "", werrors.NewNotFoundError("课件不存在")
+273 -85
View File
@@ -2,6 +2,7 @@ package service
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@@ -52,9 +53,18 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
item.Category = strings.TrimSpace(item.Category) item.Category = strings.TrimSpace(item.Category)
item.Description = strings.TrimSpace(item.Description) item.Description = strings.TrimSpace(item.Description)
item.SuitableMembers = strings.TrimSpace(item.SuitableMembers) item.SuitableMembers = strings.TrimSpace(item.SuitableMembers)
// 适合人员备注(000165):截断到列宽,参加人员名单过长时避免落库报错。
item.PostScope = truncatePostScope(item.PostScope)
item.LecturerID = strings.TrimSpace(item.LecturerID) item.LecturerID = strings.TrimSpace(item.LecturerID)
item.LecturerExternal = strings.TrimSpace(item.LecturerExternal) item.LecturerExternal = strings.TrimSpace(item.LecturerExternal)
item.MaterialName = strings.TrimSpace(item.MaterialName) item.MaterialName = strings.TrimSpace(item.MaterialName)
// 课程权限(000163):部门/人员 id 列表归一为「,」连接(去空白去重)。
item.PermDeptIDs = normalizePermIDs(item.PermDeptIDs)
item.PermUserIDs = normalizePermIDs(item.PermUserIDs)
// 课件列表(000164 多课件):新建/导入无课件时落空数组列默认值(非 NULL)。
if len(item.Materials) == 0 {
item.Materials = types.JSON([]byte("[]"))
}
if item.Type != "elective" { if item.Type != "elective" {
item.Type = "required" item.Type = "required"
} }
@@ -64,6 +74,61 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
return nil return nil
} }
// truncatePostScope 适合人员备注截断(000165):列宽 varchar(512),参加人员
// 名单过长时按 rune 截断,避免落库报错阻断保存。
func truncatePostScope(raw string) string {
runes := []rune(strings.TrimSpace(raw))
if len(runes) > 512 {
return string(runes[:512])
}
return string(runes)
}
// normalizePermIDs 课程权限 id 列表归一(000163):逗号/顿号/空白分隔 → 去空白
// 去重 → 「,」连接落库(与 string_to_array(x, ',') 匹配口径一致)。
func normalizePermIDs(raw string) string {
seen := make(map[string]bool)
out := make([]string, 0, 8)
for _, part := range strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == ',' || r == '、' || r == ' ' || r == ';' || r == ';'
}) {
id := strings.TrimSpace(part)
if id == "" || seen[id] {
continue
}
seen[id] = true
out = append(out, id)
}
return strings.Join(out, ",")
}
// setCourseMaterials 序列化课件条目列表回 JSON 列(000164 多课件)。
func setCourseMaterials(item *types.TrainingCourseLibrary, list []types.CourseLibraryMaterial) {
if len(list) == 0 {
item.Materials = types.JSON([]byte("[]"))
return
}
buf, err := json.Marshal(list)
if err != nil {
logger.Warnf(context.Background(), "Marshal course library materials failed, course=%s error: %v", item.ID, err)
return
}
item.Materials = types.JSON(buf)
}
// refreshPrimaryFromMaterials 主字段镜像(000164 多课件):file_key/file_name/
// file_size/knowledge_id 恒指向最新一条课件条目(发布校验/AI 出题/学习抽屉/
// 月计划带出等既有依赖口径不变);列表清空后主字段一并清空。
func refreshPrimaryFromMaterials(item *types.TrainingCourseLibrary) {
list := item.CourseMaterialList()
if len(list) == 0 {
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = "", "", 0, ""
return
}
latest := list[len(list)-1]
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = latest.FileKey, latest.Name, latest.Size, latest.KnowledgeID
}
// ListCourseLibraryItems 课程管理列表(月培训计划「计划名称」下拉同源)。 // ListCourseLibraryItems 课程管理列表(月培训计划「计划名称」下拉同源)。
func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) { func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
return s.repo.ListCourseLibrary(ctx, tenantID, q) return s.repo.ListCourseLibrary(ctx, tenantID, q)
@@ -96,6 +161,26 @@ func (s *trainingService) resolveCourseLibraryDept(ctx context.Context, tenantID
} }
} }
// defaultCoursePermission 课程权限默认(000165 复测):未设置任何权限(perm 两列
// 与存量 suitable_members 均为空)时默认「所属部门」可见,与前端表单默认口径
// 一致; suitable_members 同步部门名作为展示/存量匹配文本。已设置则不动。
func (s *trainingService) defaultCoursePermission(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary) {
if item.HasPermissionSet() || strings.TrimSpace(item.OwnerDeptID) == "" {
return
}
item.PermDeptIDs = item.OwnerDeptID
if strings.TrimSpace(item.SuitableMembers) == "" {
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
if d != nil && d.ID == item.OwnerDeptID {
item.SuitableMembers = strings.TrimSpace(d.Name)
break
}
}
}
}
}
// SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。 // SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。
func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) { func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) {
if err := normalizeCourseLibrary(item); err != nil { if err := normalizeCourseLibrary(item); err != nil {
@@ -109,11 +194,11 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
item.VerifyStatus = types.CourseLibraryVerifyPending item.VerifyStatus = types.CourseLibraryVerifyPending
// 仅传部门名时按组织架构解析为 id(不阻断保存)。 // 仅传部门名时按组织架构解析为 id(不阻断保存)。
s.resolveCourseLibraryDept(ctx, tenantID, item) s.resolveCourseLibraryDept(ctx, tenantID, item)
// 所属部门强制为创建人部门(000160):前端表单同口径锁定,服务端兜底 // 未填课程权限时默认「所属部门」可见(000165 复测,与前端表单默认同口径)。
// 覆盖,防止绕过前端改部门。创建人无部门档案时保留原值(可为空)。 s.defaultCoursePermission(ctx, tenantID, item)
if member, err := s.CurrentMember(ctx, tenantID, updaterID); err == nil && member != nil && member.DeptID != "" { // 所属部门默认创建人部门、支持修改(000165):前端表单默认当前登录人
item.OwnerDeptID = member.DeptID // 部门,不再服务端强制覆盖(000160 的强制口径放开);留空时保持为空,
} // 审核前由审核校验兜底拦截。
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。 // 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
item.Code = s.nextCourseLibraryCode(ctx, tenantID) item.Code = s.nextCourseLibraryCode(ctx, tenantID)
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil { if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
@@ -126,21 +211,22 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
if err != nil || old == nil { if err != nil || old == nil {
return nil, werrors.NewNotFoundError("课程不存在") return nil, werrors.NewNotFoundError("课程不存在")
} }
// 课件文件:移除标记强制清空;未重新上传时保留原文件信息 // 课件列表(000164 多课件)不随表单回传:编辑保存保持原列表;课件文件字段
// (表单不回传 file_key,零值会被误清)。 // 由列表镜像刷新(原 file_key 零值误清保护收敛到镜像逻辑;ClearFile 移除
// 标记保留兼容,置 true 时整体清空课件)。
item.Materials = old.Materials
if item.ClearFile { if item.ClearFile {
item.FileKey, item.FileName, item.FileSize = "", "", 0 setCourseMaterials(item, nil)
item.KnowledgeID = ""
} else if item.FileKey == "" && item.FileName == "" && item.FileSize == 0 {
item.FileKey, item.FileName, item.FileSize = old.FileKey, old.FileName, old.FileSize
} }
// 知识库文档 id 不随表单回传:未重新上传时保留原值(与新文件一并覆盖)。 refreshPrimaryFromMaterials(item)
if item.KnowledgeID == "" { // 所属部门支持修改(000165):请求携带新值即按新值更新;未传(空值)时
item.KnowledgeID = old.KnowledgeID // 保持创建时的部门,防止全量更新误清(000160 的不可修改口径放开)。
if strings.TrimSpace(item.OwnerDeptID) == "" {
item.OwnerDeptID = old.OwnerDeptID
} }
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。 // 编辑即回待审核(000157):课程信息(名称/部门/权限等)变更后原审核结论
item.OwnerDeptID = old.OwnerDeptID // 作废,需重新审核;课件/试题变更例外 —— 000165 复测起不回待审核
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。 // (课件走上传/知识库挂接专端点,不走本表单保存)。
item.VerifyStatus = types.CourseLibraryVerifyPending item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = "" item.ConfirmedBy = ""
item.ConfirmedAt = nil item.ConfirmedAt = nil
@@ -153,14 +239,15 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
// DeleteCourseLibraryItem 软删课程管理条目(月培训计划已创建的历史计划不受影响)。 // DeleteCourseLibraryItem 软删课程管理条目(月培训计划已创建的历史计划不受影响)。
// 000157 收紧:仅「待核验」状态可删(已确认课程须走核验流程,不可绕过); // 000157 收紧:仅「待核验」状态可删(已确认课程须走核验流程,不可绕过);
// deptScope 非空(课长/经理)时仅可删除本部门课程。 // deptScope 非空(课长/经理)时仅可删除本部门课程。bySuperAdmin(超级管理员
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string) error { // 职称角色/空间 Owner 兜底)放开终态:已审核/已发布课程与跨部门均可删。
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string, bySuperAdmin bool) error {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id) item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil { if err != nil || item == nil {
return werrors.NewNotFoundError("课程不存在") return werrors.NewNotFoundError("课程不存在")
} }
if item.VerifyStatus != types.CourseLibraryVerifyPending { if item.VerifyStatus != types.CourseLibraryVerifyPending && !bySuperAdmin {
return werrors.NewBadRequestError("仅待核验状态的课程可删除,已确认课程不可删除") return werrors.NewBadRequestError("仅待审核状态的课程可删除,已审核课程仅超级管理员可删除")
} }
if deptScope != "" && item.OwnerDeptID != deptScope { if deptScope != "" && item.OwnerDeptID != deptScope {
return werrors.NewForbiddenError("仅可删除本部门的课程") return werrors.NewForbiddenError("仅可删除本部门的课程")
@@ -192,17 +279,24 @@ func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, ten
if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed { if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed {
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name)) return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name))
} }
if status == "published" && strings.TrimSpace(item.FileKey) == "" && strings.TrimSpace(item.KnowledgeID) == "" { if status == "published" && !item.HasCourseMaterial() {
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name)) return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name))
} }
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status) return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
} }
// VerifyCourseLibraryItems 批量核验课程条目(000157,单个/批量共用):核验人所在 // VerifyCourseLibraryItems 批量审核课程条目(000163:核验升级为「审核」,审核
// 部门(deptScope,handler 保证恒非空)必须与课程所属部门一致;已确认行与部门 // 通过即自动发布;单个/批量共用):审核人所在部门(deptScope,handler 保证恒
// 不匹配行跳过,返回实际核验数与跳过数,全无效时报错提示。 // 非空)必须与课程所属部门一致;已确认行与部门不匹配行跳过。
func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (int64, int64, error) { // 审核前置(测试反馈 2026-11-26):课程权限必填 —— perm 两列与存量 suitable_members
// 均为空的课程拒绝审核,整批报错定位到具体课程。
// 审核通过后:已有课件(原始文件或知识库挂接)的课程同步置为已发布,无需再点
// 「发布」;未上传课件的课程保持待发布,上传课件重新审核后自动发布。
func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (*interfaces.CourseLibraryVerifyResult, error) {
result := &interfaces.CourseLibraryVerifyResult{UnpublishedNames: []string{}}
allowed := make([]string, 0, len(ids)) allowed := make([]string, 0, len(ids))
// 可自动发布(审核通过 + 已传课件)与待补课件(审核通过未传课件)分桶。
publishable := make([]string, 0, len(ids))
for _, id := range ids { for _, id := range ids {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id) item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil { if err != nil || item == nil {
@@ -211,21 +305,55 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
if item.VerifyStatus != types.CourseLibraryVerifyPending { if item.VerifyStatus != types.CourseLibraryVerifyPending {
continue // 已确认行幂等跳过 continue // 已确认行幂等跳过
} }
// 所属部门必填(000165 审核校验):先于部门归属判断,空部门行给出
// 明确拦截提示而非静默跳过("没有可审核的课程"难定位)。
if strings.TrimSpace(item.OwnerDeptID) == "" {
return nil, werrors.NewBadRequestError(
fmt.Sprintf("课程《%s》未设置所属部门,请先在课程管理中设置所属部门后再审核", item.Name))
}
if deptScope != "" && item.OwnerDeptID != deptScope { if deptScope != "" && item.OwnerDeptID != deptScope {
continue // 课长/经理仅可核验本部门课程 continue // 课长/经理仅可审核本部门课程
}
// 课程权限必填(审核前置):权限两列与存量适合人员均未设置时拦截。
if !item.HasPermissionSet() {
return nil, werrors.NewBadRequestError(
fmt.Sprintf("课程《%s》未设置课程权限,请先在课程管理中设置课程权限后再审核", item.Name))
}
// 课件必填(000165 审核校验):审核即发布,无课件课程不再放行审核,
// 须先在列表「课件」入口上传课件文件(或从知识库选择)。
if !item.HasCourseMaterial() {
return nil, werrors.NewBadRequestError(
fmt.Sprintf("课程《%s》未上传课件,请先在列表「课件」入口上传课件后再审核", item.Name))
} }
allowed = append(allowed, id) allowed = append(allowed, id)
if item.HasCourseMaterial() {
publishable = append(publishable, id)
} else {
result.UnpublishedNames = append(result.UnpublishedNames, item.Name)
}
} }
skipped := int64(len(ids) - len(allowed)) result.Skipped = int64(len(ids) - len(allowed))
if len(allowed) == 0 { if len(allowed) == 0 {
return 0, skipped, werrors.NewBadRequestError("没有可核验的课程(仅本部门待核验状态的课程可核验)") return nil, werrors.NewBadRequestError("没有可审核的课程(仅本部门待审核状态的课程可审核)")
} }
verified, err := s.repo.ConfirmCourseLibraryItems(ctx, tenantID, allowed, verifierID) verified, err := s.repo.ConfirmCourseLibraryItems(ctx, tenantID, allowed, verifierID)
if err != nil { if err != nil {
return 0, 0, err return nil, err
} }
logger.Infof(ctx, "[Training] course library verified, tenant=%d verified=%d skipped=%d verifier=%s", tenantID, verified, skipped, verifierID) result.Verified = verified
return verified, skipped, nil // 审核即发布(000163):已传课件的条目同步置为已发布,培训中心「和信课程」
// 与月/年培训计划选课立即可见(按课程权限)。发布失败不回滚审核,仅记日志。
if len(publishable) > 0 {
for _, id := range publishable {
if perr := s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, "published"); perr != nil {
logger.Warnf(ctx, "Auto publish after course verify failed, tenant=%d course=%s error: %v", tenantID, id, perr)
continue
}
result.AutoPublished++
}
}
logger.Infof(ctx, "[Training] course library verified&published, tenant=%d verified=%d skipped=%d auto_published=%d verifier=%s", tenantID, result.Verified, result.Skipped, result.AutoPublished, verifierID)
return result, nil
} }
// matchOrCreateLibraryCourse 需求侧课程校验(000158):按课程名称在课程管理精准 // matchOrCreateLibraryCourse 需求侧课程校验(000158):按课程名称在课程管理精准
@@ -255,6 +383,7 @@ func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenant
OwnerDeptID: proto.OwnerDeptID, OwnerDeptID: proto.OwnerDeptID,
Category: strings.TrimSpace(proto.Category), Category: strings.TrimSpace(proto.Category),
SuitableMembers: strings.TrimSpace(proto.SuitableMembers), SuitableMembers: strings.TrimSpace(proto.SuitableMembers),
PostScope: truncatePostScope(proto.PostScope),
LecturerID: proto.LecturerID, LecturerID: proto.LecturerID,
LecturerExternal: strings.TrimSpace(proto.LecturerExternal), LecturerExternal: strings.TrimSpace(proto.LecturerExternal),
Type: "required", Type: "required",
@@ -262,6 +391,7 @@ func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenant
PublishStatus: "draft", PublishStatus: "draft",
VerifyStatus: types.CourseLibraryVerifyPending, VerifyStatus: types.CourseLibraryVerifyPending,
CreatorID: creatorID, CreatorID: creatorID,
Materials: types.JSON([]byte("[]")),
} }
if item.LecturerID != "" { if item.LecturerID != "" {
item.LecturerExternal = "" item.LecturerExternal = ""
@@ -280,12 +410,29 @@ func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID
return 0, werrors.NewBadRequestError("没有可导入的课程数据") return 0, werrors.NewBadRequestError("没有可导入的课程数据")
} }
rows := make([]*types.TrainingCourseLibrary, 0, len(items)) rows := make([]*types.TrainingCourseLibrary, 0, len(items))
// 部门 id→名映射(000165 复测:未填课程权限的行默认「所属部门」可见时,同步部门名)
deptNameByID := map[string]string{}
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
if d != nil && strings.TrimSpace(d.Name) != "" {
deptNameByID[d.ID] = strings.TrimSpace(d.Name)
}
}
}
for _, item := range items { for _, item := range items {
if err := normalizeCourseLibrary(item); err != nil { if err := normalizeCourseLibrary(item); err != nil {
continue // 缺课程名称的行跳过(前端同步提示跳过行数) continue // 缺课程名称的行跳过(前端同步提示跳过行数)
} }
// 仅传部门名的行按组织架构解析为 id(前端匹配失败/未传 id 的兜底)。 // 仅传部门名的行按组织架构解析为 id(前端匹配失败/未传 id 的兜底)。
s.resolveCourseLibraryDept(ctx, tenantID, item) s.resolveCourseLibraryDept(ctx, tenantID, item)
// 000165 复测:未填课程权限的导入行默认「所属部门」可见(与新增表单默认同口径),
// suitable_members 同步部门名作为展示/存量匹配文本;已设置(含存量自由文本)则不动。
if !item.HasPermissionSet() && strings.TrimSpace(item.OwnerDeptID) != "" {
item.PermDeptIDs = item.OwnerDeptID
if strings.TrimSpace(item.SuitableMembers) == "" {
item.SuitableMembers = deptNameByID[item.OwnerDeptID]
}
}
item.ID = trainingNewID() item.ID = trainingNewID()
item.TenantID = tenantID item.TenantID = tenantID
item.CreatorID = updaterID item.CreatorID = updaterID
@@ -363,8 +510,12 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
return filename, buf.Bytes(), nil return filename, buf.Bytes(), nil
} }
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key,不入知识库 // UploadCourseLibraryMaterial 上传课件原始文件(000164 多课件:追加课件条目,
// 解析链路;名称登记与文件可并存)。 // 不再替换既有课件)。fileSvc 落 file_key,不入知识库解析链路;文档类同步知识库
// 「企业培训(课件)」(000153:AI 出题与对话问答依赖知识库分块;视频类仅存原始
// 文件,同步失败 fail-open 退回原始文件存取)。主字段(file_*/knowledge_id)镜像
// 最新一条,发布校验/AI 出题/学习抽屉等既有依赖口径不变;课件变更不回待审核
// (000165 复测,详见 UploadCourseLibraryMaterial)。
func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error) { func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error) {
if fh == nil { if fh == nil {
return nil, werrors.NewBadRequestError("缺少上传文件") return nil, werrors.NewBadRequestError("缺少上传文件")
@@ -378,11 +529,14 @@ func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenan
logger.Errorf(ctx, "Failed to save course library material, error: %v", err) logger.Errorf(ctx, "Failed to save course library material, error: %v", err)
return nil, err return nil, err
} }
item.FileKey = fileKey entry := types.CourseLibraryMaterial{
item.FileName = fh.Filename Mid: trainingNewID(),
item.FileSize = fh.Size Name: fh.Filename,
// 文档类课件同步知识库「企业培训(课件)」(000153:AI 出题与对话问答依赖 Size: fh.Size,
// 知识库分块;视频类仍只存原始文件)。同步失败 fail-open,退回原始文件存取。 FileKey: fileKey,
Origin: "upload",
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
if !isVideoMaterialFile("", fh.Filename) { if !isVideoMaterialFile("", fh.Filename) {
coursewareKB, _, kbErr := s.ensureTrainingKnowledgeBases(ctx) coursewareKB, _, kbErr := s.ensureTrainingKnowledgeBases(ctx)
if kbErr != nil { if kbErr != nil {
@@ -390,80 +544,112 @@ func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenan
} else if knowledgeID, syncErr := s.syncFileToKnowledgeBase(ctx, coursewareKB.ID, fh, ""); syncErr != nil { } 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) logger.Warnf(ctx, "Skip syncing course library material to knowledge base (upload failed): %v", syncErr)
} else { } else {
item.KnowledgeID = knowledgeID entry.KnowledgeID = knowledgeID
} }
} else {
item.KnowledgeID = ""
} }
// 名称登记为空时以文件名兜底,便于列表直接识别课件。 // 追加课件条目(不替换),主字段镜像为最新条;名称登记为空时以首个文件名兜底。
setCourseMaterials(item, append(item.CourseMaterialList(), entry))
refreshPrimaryFromMaterials(item)
if strings.TrimSpace(item.MaterialName) == "" { if strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = fh.Filename item.MaterialName = fh.Filename
} }
// 换课件即回待核验(000157):课件内容变更后需重新核验。 // 课件变更不再回待审核(000165 复测):课件/试题调整视为培训资料更新,
item.VerifyStatus = types.CourseLibraryVerifyPending // 课程信息(名称/部门/权限等)未变则维持原审核结论,月计划可直接发布;
item.ConfirmedBy = "" // 上传的课件即作为本次培训课件(学习抽屉/计划课件均取最新条)。
item.ConfirmedAt = nil
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil { if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err return nil, err
} }
logger.Infof(ctx, "[Training] course library material uploaded, tenant=%d course=%s size=%d uploader=%s", tenantID, id, fh.Size, updaterID) logger.Infof(ctx, "[Training] course library material appended, tenant=%d course=%s materials=%d size=%d uploader=%s", tenantID, id, len(item.CourseMaterialList()), fh.Size, updaterID)
return item, nil return item, nil
} }
// GetCourseLibraryMaterialFile 流式取回课件原始文件:文档类优先按知识库文档 // GetCourseLibraryMaterialFile 流式取回课件原始文件(000164:mid 定位具体课件
// 取回流(000153 同步入库后与月计划课件同口径),视频/同步失败回退 file_key。 // 条目,空 = 最新一条兼容旧调用):文档类优先按知识库文档取回流(000153 同步入库
func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error) { // 后与月计划课件同口径),视频/同步失败回退 file_key。
func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id, mid string) (io.ReadCloser, string, error) {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id) item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil { if err != nil || item == nil {
return nil, "", werrors.NewNotFoundError("课程不存在") return nil, "", werrors.NewNotFoundError("课程不存在")
} }
if item.FileKey == "" && item.KnowledgeID == "" { entry := item.PrimaryCourseMaterial()
if mid != "" {
entry = nil
for i := range item.CourseMaterialList() {
if item.CourseMaterialList()[i].Mid == mid {
entry = &item.CourseMaterialList()[i]
break
}
}
}
if entry == nil || (entry.FileKey == "" && entry.KnowledgeID == "") {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件") return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
} }
if item.KnowledgeID != "" { if entry.KnowledgeID != "" {
rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, item.KnowledgeID) rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, entry.KnowledgeID)
if err == nil { if err == nil {
// 下载文件名沿用登记名(知识库文档名可能与登记名不一致)。 // 下载文件名沿用条目名(知识库文档名可能与登记名不一致)。
return rc, item.FileName, nil return rc, entry.Name, nil
} }
logger.Warnf(ctx, "Fallback to raw file for course library material, course: %s, error: %v", id, err) logger.Warnf(ctx, "Fallback to raw file for course library material, course: %s, error: %v", id, err)
} }
if item.FileKey == "" { if entry.FileKey == "" {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件") return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
} }
rc, err := s.fileSvc.GetFile(ctx, item.FileKey) rc, err := s.fileSvc.GetFile(ctx, entry.FileKey)
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }
return rc, item.FileName, nil return rc, entry.Name, nil
} }
// RemoveCourseLibraryMaterial 移除课程课件原始文件/知识库挂接(名称登记保留, // RemoveCourseLibraryMaterial 移除课件条目(000164 多课件:按 mid 定位,mid 空 =
// 上传课件时仍会以文件名兜底名称登记):文件与知识库文档字段清空,课件内容 // 移除最新一条兼容旧调用):文件与知识库挂接随条目移除,名称登记保留;主字段镜像
// 变更即回待核验(000157 同口径),移除后课程不满足发布课件前置。 // 回退为剩余最新条(无剩余则清空);课件变更不回待审核(000165 复测同上传口径)。
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) { // 未跑
// 000164 回填的存量行(列表为空而主字段有课件)按清空主字段兜底。
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, mid, updaterID string) (*types.TrainingCourseLibrary, error) {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id) item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil { if err != nil || item == nil {
return nil, werrors.NewNotFoundError("课程不存在") return nil, werrors.NewNotFoundError("课程不存在")
} }
if item.FileKey == "" && item.KnowledgeID == "" { list := item.CourseMaterialList()
return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除") if len(list) == 0 {
if item.FileKey == "" && item.KnowledgeID == "" {
return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除")
}
// 存量行兜底:课件列表为空时按清空主字段处理(旧口径)。
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = "", "", 0, ""
} else {
idx := -1
if mid == "" {
idx = len(list) - 1
} else {
for i := range list {
if list[i].Mid == mid {
idx = i
break
}
}
}
if idx < 0 {
return nil, werrors.NewNotFoundError("课件条目不存在或已移除")
}
removed := list[idx]
list = append(list[:idx], list[idx+1:]...)
setCourseMaterials(item, list)
refreshPrimaryFromMaterials(item)
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s material=%s operator=%s", tenantID, id, removed.Mid, updaterID)
} }
item.FileKey, item.FileName, item.FileSize = "", "", 0 // 课件移除同上传口径(000165 复测):不回待审核,维持原审核结论。
item.KnowledgeID = ""
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil { if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err return nil, err
} }
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s operator=%s", tenantID, id, updaterID)
return item, nil return item, nil
} }
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有 // AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。 // 文档作为课程课件(000164 多课件:追加条目,不替换;与上传同口径,下载/月计划
// 原始文件字段清空,名称登记为空时以文档名兜底。 // 课件挂接/AI 出题共用 knowledge_id)。
func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) { func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) {
knowledgeID = strings.TrimSpace(knowledgeID) knowledgeID = strings.TrimSpace(knowledgeID)
if knowledgeID == "" { if knowledgeID == "" {
@@ -481,21 +667,23 @@ func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.C
if name == "" { if name == "" {
name = strings.TrimSpace(doc.Title) name = strings.TrimSpace(doc.Title)
} }
if name != "" { entry := types.CourseLibraryMaterial{
item.FileName = name Mid: trainingNewID(),
if strings.TrimSpace(item.MaterialName) == "" { Name: name,
item.MaterialName = name Size: doc.FileSize,
} KnowledgeID: knowledgeID,
Origin: "kb",
CreatedAt: time.Now().UTC().Format(time.RFC3339),
} }
item.FileKey, item.FileSize = "", 0 setCourseMaterials(item, append(item.CourseMaterialList(), entry))
item.KnowledgeID = knowledgeID refreshPrimaryFromMaterials(item)
// 换课件即回待核验(000157):课件内容变更后需重新核验。 if name != "" && strings.TrimSpace(item.MaterialName) == "" {
item.VerifyStatus = types.CourseLibraryVerifyPending item.MaterialName = name
item.ConfirmedBy = "" }
item.ConfirmedAt = nil // 知识库挂课件同上传口径(000165 复测):不回待审核,维持原审核结论。
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil { if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err 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) logger.Infof(ctx, "[Training] course library material attached from knowledge base, tenant=%d course=%s knowledge=%s materials=%d operator=%s", tenantID, id, knowledgeID, len(item.CourseMaterialList()), updaterID)
return item, nil return item, nil
} }
@@ -2,6 +2,7 @@ package service
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -98,26 +99,27 @@ func TestRemoveCourseLibraryMaterial(t *testing.T) {
} }
seedCourseLibraryItem(t, db, tenantID, item) seedCourseLibraryItem(t, db, tenantID, item)
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op") updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "", "u-op")
require.NoError(t, err) require.NoError(t, err)
require.Empty(t, updated.FileKey) require.Empty(t, updated.FileKey)
require.Empty(t, updated.FileName) require.Empty(t, updated.FileName)
require.Zero(t, updated.FileSize) require.Zero(t, updated.FileSize)
require.Empty(t, updated.KnowledgeID) require.Empty(t, updated.KnowledgeID)
require.Equal(t, "登记名称保留", updated.MaterialName) require.Equal(t, "登记名称保留", updated.MaterialName)
require.Equal(t, types.CourseLibraryVerifyPending, updated.VerifyStatus) // 课件移除不再回待审核(000165 复测):维持原审核结论与核验痕迹。
require.Empty(t, updated.ConfirmedBy) require.Equal(t, types.CourseLibraryVerifyConfirmed, updated.VerifyStatus)
require.Nil(t, updated.ConfirmedAt) require.Equal(t, "u-verifier", updated.ConfirmedBy)
require.NotNil(t, updated.ConfirmedAt)
// 落库复核(更新为全列覆盖,防只改内存对象)。 // 落库复核(更新为全列覆盖,防只改内存对象)。
stored, err := svc.GetCourseLibraryItem(ctx, tenantID, item.ID) stored, err := svc.GetCourseLibraryItem(ctx, tenantID, item.ID)
require.NoError(t, err) require.NoError(t, err)
require.Empty(t, stored.FileKey) require.Empty(t, stored.FileKey)
require.Empty(t, stored.KnowledgeID) require.Empty(t, stored.KnowledgeID)
require.Equal(t, types.CourseLibraryVerifyPending, stored.VerifyStatus) require.Equal(t, types.CourseLibraryVerifyConfirmed, stored.VerifyStatus)
// 已无课件再移除:拒绝。 // 已无课件再移除:拒绝。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op") _, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "", "u-op")
require.Error(t, err) require.Error(t, err)
} }
@@ -126,6 +128,105 @@ func timeNowPtr() *time.Time {
return &v return &v
} }
// 审核(000163:核验升级为审核,审核通过即自动发布;000165 补充审核必填校验):
// - 课程权限必填:perm 两列与 suitable_members 均为空的课程整批拒绝;
// - 课件必填(000165):审核即发布,未传课件的课程整批拒绝;
// - 名称/所属部门/权限/课件齐备的课程审核通过即自动发布(published)。
func TestVerifyCourseLibraryItemsRequiresPermissionAndAutoPublish(t *testing.T) {
svc, db, tenantID := newCourseLibraryFixture(t)
ctx := context.Background()
noPerm := &types.TrainingCourseLibrary{ID: "cl-noperm", Name: "未设置权限课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, FileKey: "fk-1", FileName: "a.pptx"}
permAndFile := &types.TrainingCourseLibrary{ID: "cl-ok", Name: "权限加课件课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-1", FileKey: "fk-2", FileName: "b.pptx"}
permNoFile := &types.TrainingCourseLibrary{ID: "cl-nofile", Name: "权限缺课件课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, SuitableMembers: "全部"}
noDept := &types.TrainingCourseLibrary{ID: "cl-nodept", Name: "缺部门课程", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-1", FileKey: "fk-3", FileName: "c.pptx"}
otherDept := &types.TrainingCourseLibrary{ID: "cl-other", Name: "别部门课程", OwnerDeptID: "dept-2", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-2"}
for _, item := range []*types.TrainingCourseLibrary{noPerm, permAndFile, permNoFile, noDept, otherDept} {
seedCourseLibraryItem(t, db, tenantID, item)
}
// 课程权限未设置:整批拒绝并点名课程。
_, err := svc.VerifyCourseLibraryItems(ctx, tenantID, []string{noPerm.ID}, "u-verifier", "dept-1")
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "课程权限"), "应提示未设置课程权限,实际: %s", err.Error())
// 课件必填(000165):权限已设置但未上传课件,整批拒绝并点名课程。
_, err = svc.VerifyCourseLibraryItems(ctx, tenantID, []string{permNoFile.ID}, "u-verifier", "dept-1")
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "课件"), "应提示未上传课件,实际: %s", err.Error())
// 所属部门必填(000165):部门为空时整批拒绝并点名课程。
_, err = svc.VerifyCourseLibraryItems(ctx, tenantID, []string{noDept.ID}, "u-verifier", "dept-1")
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "所属部门"), "应提示未设置所属部门,实际: %s", err.Error())
// 部门不匹配:跳过,无可用条目报错。
_, err = svc.VerifyCourseLibraryItems(ctx, tenantID, []string{otherDept.ID}, "u-verifier", "dept-1")
require.Error(t, err)
// 齐备批次:确认并自动发布;部门不匹配行跳过。
res, err := svc.VerifyCourseLibraryItems(ctx, tenantID, []string{permAndFile.ID, otherDept.ID}, "u-verifier", "dept-1")
require.NoError(t, err)
require.EqualValues(t, 1, res.Verified)
require.EqualValues(t, 1, res.Skipped)
require.EqualValues(t, 1, res.AutoPublished)
require.Empty(t, res.UnpublishedNames)
stored, err := svc.GetCourseLibraryItem(ctx, tenantID, permAndFile.ID)
require.NoError(t, err)
require.Equal(t, types.CourseLibraryVerifyConfirmed, stored.VerifyStatus)
require.Equal(t, "published", stored.PublishStatus)
// 缺课件行未被审核:仍为待审核/草稿。
storedNoFile, err := svc.GetCourseLibraryItem(ctx, tenantID, permNoFile.ID)
require.NoError(t, err)
require.Equal(t, types.CourseLibraryVerifyPending, storedNoFile.VerifyStatus)
require.Equal(t, "draft", storedNoFile.PublishStatus)
}
// 多课件(000164):课件列表追加不替换,主字段镜像最新条;按 mid 移除后主字段
// 回退为剩余最新条,全部移除后主字段清空,再移除报错。
func TestCourseLibraryMultiMaterialsRemoveByMid(t *testing.T) {
svc, db, tenantID := newCourseLibraryFixture(t)
ctx := context.Background()
m1 := types.CourseLibraryMaterial{Mid: "m-1", Name: "a.pptx", Size: 1, FileKey: "fk-1", Origin: "upload"}
m2 := types.CourseLibraryMaterial{Mid: "m-2", Name: "b.docx", Size: 2, KnowledgeID: "kb-2", Origin: "kb"}
buf, err := json.Marshal([]types.CourseLibraryMaterial{m1, m2})
require.NoError(t, err)
seed := &types.TrainingCourseLibrary{
ID: "cl-multi", Name: "多课件课程", OwnerDeptID: "dept-1",
Materials: types.JSON(buf),
// 主字段镜像最新条 m-2。
FileKey: "", FileName: "b.docx", FileSize: 2, KnowledgeID: "kb-2",
VerifyStatus: types.CourseLibraryVerifyPending,
}
seedCourseLibraryItem(t, db, tenantID, seed)
// 按 mid 移除首条:剩余最新条 b.docx 镜像到主字段。
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-1", "u-op")
require.NoError(t, err)
require.Len(t, updated.CourseMaterialList(), 1)
require.Equal(t, "m-2", updated.CourseMaterialList()[0].Mid)
require.Equal(t, "kb-2", updated.KnowledgeID)
require.Equal(t, "b.docx", updated.FileName)
require.Equal(t, types.CourseLibraryVerifyPending, updated.VerifyStatus)
// 移除不存在的 mid:报错不误删。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-x", "u-op")
require.Error(t, err)
// 移除最后一条:列表清空、主字段一并清空。
updated, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-2", "u-op")
require.NoError(t, err)
require.Empty(t, updated.CourseMaterialList())
require.Empty(t, updated.FileKey)
require.Empty(t, updated.KnowledgeID)
// 已无课件再移除:报错。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "", "u-op")
require.Error(t, err)
}
// 计划「形式」与课程「线上/线下」独立(000162):绑定带出名称/类型,不覆盖 // 计划「形式」与课程「线上/线下」独立(000162):绑定带出名称/类型,不覆盖
// 计划侧 mode——课程线下 + 计划线上、课程线上 + 计划线下双向保持请求值。 // 计划侧 mode——课程线下 + 计划线上、课程线上 + 计划线下双向保持请求值。
func TestApplyLibraryCourseBindingKeepsPlanMode(t *testing.T) { func TestApplyLibraryCourseBindingKeepsPlanMode(t *testing.T) {
@@ -130,7 +130,7 @@ type notifyTextTemplates struct {
// 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。 // 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。
const ( const (
defaultStudentNoticeTitle = "培训开课通知" defaultStudentNoticeTitle = "培训开课通知"
defaultStudentNoticeContent = "您被点名参加「{course}」培训:{time},{place},讲师:{lecturer}。请准时参加。" defaultStudentNoticeContent = "诚邀您参加「{course}」,培训时间:{time},培训地点:{place},培训讲师:{lecturer},请提前安排好工作,准时参加,谢谢!"
defaultLecturerOpenTitle = "授课提醒" defaultLecturerOpenTitle = "授课提醒"
defaultLecturerOpenFooter = "请准时参加,详情见培训平台。" defaultLecturerOpenFooter = "请准时参加,详情见培训平台。"
defaultLecturerMaintainTitle = "课程维护提醒" defaultLecturerMaintainTitle = "课程维护提醒"
@@ -139,7 +139,7 @@ const (
defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。" defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
// 年培训计划收集推送默认文案(与前端收集弹窗历史硬编码逐字一致;{year} 渲染收集年度) // 年培训计划收集推送默认文案(与前端收集弹窗历史硬编码逐字一致;{year} 渲染收集年度)
defaultDemandCollectTitle = "【培训需求收集】{year}年度培训计划收集" defaultDemandCollectTitle = "【培训需求收集】{year}年度培训计划收集"
defaultDemandCollectContent = "请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。" defaultDemandCollectContent = "请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录和信智汇学院 → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。"
) )
func defaultNotifyTextTemplates() notifyTextTemplates { func defaultNotifyTextTemplates() notifyTextTemplates {
@@ -253,7 +253,15 @@ func (s *trainingService) sessionNoticeText(ctx context.Context, tenantID uint64
place = "线上会议(链接见课程页)" place = "线上会议(链接见课程页)"
} }
lecturerName := "待定" lecturerName := "待定"
if lecturer, err := s.repo.GetMember(ctx, tenantID, session.LecturerID); err == nil && lecturer != nil && lecturer.UserName != "" { // 讲师解析兜底(000165 复测):场次未指定讲师时回退课程管理主数据的讲师,
// 避免课程已设讲师但通知仍显示「待定」(场次先建、讲师后补的场景)。
lecturerID := session.LecturerID
if strings.TrimSpace(lecturerID) == "" {
if course, err := s.repo.GetCourse(ctx, tenantID, session.CourseID); err == nil && course != nil {
lecturerID = course.LecturerID
}
}
if lecturer, err := s.repo.GetMember(ctx, tenantID, lecturerID); err == nil && lecturer != nil && lecturer.UserName != "" {
lecturerName = lecturer.UserName lecturerName = lecturer.UserName
} }
tpl := s.loadNotifyTextTemplates(ctx, tenantID) tpl := s.loadNotifyTextTemplates(ctx, tenantID)
@@ -593,6 +601,8 @@ func demandCollectYear(refID string, now time.Time) int {
const demandCollectPlanPath = "/platform/training/plan" const demandCollectPlanPath = "/platform/training/plan"
// wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。 // wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。
// 000165 复测:学员开课通知(session_notice_student)与开课提醒统一为 markdown
// 样式 —— 站内标题加粗置顶(如【培训开课通知】),正文随配置模板。
// demand_collect 且行内带 link_url 时追加两行 markdown 链接: // demand_collect 且行内带 link_url 时追加两行 markdown 链接:
// //
// 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略) // 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略)
@@ -600,6 +610,14 @@ const demandCollectPlanPath = "/platform/training/plan"
// //
// 其余场景原样返回(提醒类场景的 markdown 由生成侧 remindContent 拼好)。 // 其余场景原样返回(提醒类场景的 markdown 由生成侧 remindContent 拼好)。
func wecomDispatchContent(row *claimedNotification) string { func wecomDispatchContent(row *claimedNotification) string {
if row.Scene == types.SceneSessionNoticeStudent {
var b strings.Builder
if title := strings.TrimSpace(row.Title); title != "" {
b.WriteString("**【" + title + "】**\n")
}
b.WriteString(strings.TrimSpace(row.Content))
return b.String()
}
if row.Scene != types.SceneDemandCollect || row.LinkURL == "" { if row.Scene != types.SceneDemandCollect || row.LinkURL == "" {
return row.Content return row.Content
} }
@@ -347,42 +347,54 @@ func (s *TrainingScheduler) generateForTenant(
// 立即入队(training_notify.go),调度器不再发学员 remind_tN 重复打扰; // 立即入队(training_notify.go),调度器不再发学员 remind_tN 重复打扰;
// day_before 场次在 T-1 且课件就绪时在此入队(课件缺失跳过,上传课件后 // day_before 场次在 T-1 且课件就绪时在此入队(课件缺失跳过,上传课件后
// 补推钩子兜底)。讲师 remind_tN_lecturer 授课提醒保持不变。 // 补推钩子兜底)。讲师 remind_tN_lecturer 授课提醒保持不变。
// 000165 复测:多档提醒窗口(T-3/T-1)同时过期时(临近创建/改期的场次),
// 一次扫描只发最近一档(按天升序取最小),避免同屏重复轰炸;
// 正常节奏(提前数天创建)不受影响 —— 未到窗口的档位不会入选。
dueDay := 0
for _, d := range cfg.remindDays { for _, d := range cfg.remindDays {
if now.Before(start.Add(-time.Duration(d) * 24 * time.Hour)) { if now.Before(start.Add(-time.Duration(d) * 24 * time.Hour)) {
continue continue
} }
if dueDay == 0 || d < dueDay {
dueDay = d
}
}
if dueDay > 0 {
if sess.LecturerID != "" { if sess.LecturerID != "" {
rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID, rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID,
types.TrainingRemindScene(d, true), types.TrainingRemindScene(dueDay, true),
remindTitle(cfg.texts.LecturerOpenTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter), remindTitle(cfg.texts.LecturerOpenTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
sess.ID, cfg.pushEnabled, now)} sess.ID, cfg.pushEnabled, now)}
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil { if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
return err return err
} }
} }
if sess.NotifyMode != types.TrainingNotifyModeDayBefore || d != 1 { if sess.NotifyMode == types.TrainingNotifyModeDayBefore && dueDay == 1 {
continue hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID)
} if err != nil {
hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID) return err
if err != nil { }
return err if hasMaterial {
} targets, err := s.sessionTargets(ctx, tenantID, sess)
if !hasMaterial { if err != nil {
continue return err
} }
targets, err := s.sessionTargets(ctx, tenantID, sess) rows := make([]*types.TrainingNotification, 0, len(targets))
if err != nil { for _, uid := range targets {
return err // 讲师已有同场次的授课提醒(remind_t1_lecturer),
} // 学员通知跳过讲师,避免同一人收到两条相同内容
rows := make([]*types.TrainingNotification, 0, len(targets)) if sess.LecturerID != "" && uid == sess.LecturerID {
for _, uid := range targets { continue
rows = append(rows, s.newReminderRow(tenantID, uid, }
types.SceneSessionNoticeStudent, rows = append(rows, s.newReminderRow(tenantID, uid,
remindTitle(cfg.texts.StudentNoticeTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter), types.SceneSessionNoticeStudent,
sess.ID, cfg.pushEnabled, now)) remindTitle(cfg.texts.StudentNoticeTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
} sess.ID, cfg.pushEnabled, now))
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil { }
return err if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
return err
}
}
} }
} }
@@ -426,17 +426,20 @@ const (
courseLibOptColDept = "CA" // 所属部门(组织架构部门) courseLibOptColDept = "CA" // 所属部门(组织架构部门)
courseLibOptColCat = "CB" // 课程分类(配置中心字典) courseLibOptColCat = "CB" // 课程分类(配置中心字典)
courseLibOptColLect = "CC" // 讲师(员工档案) courseLibOptColLect = "CC" // 讲师(员工档案)
courseLibOptColName = "CD" // 课程名称(课程管理既有课程,000165 复测新增)
courseLibTargetRows = 500 // 下拉覆盖的数据行数(表头在第 1 行,数据区 2~501 行) courseLibTargetRows = 500 // 下拉覆盖的数据行数(表头在第 1 行,数据区 2~501 行)
courseLibMemberLimit = 2000 // 员工档案下拉取值上限 courseLibMemberLimit = 2000 // 员工档案下拉取值上限
) )
// enrichCourseLibraryTemplate 给课程管理导入模板(内置默认/自定义 xlsx 版)动态注入 // enrichCourseLibraryTemplate 给课程管理导入模板(内置默认/自定义 xlsx 版)动态注入
// 下拉选择(表头在第 1 行): // 下拉选择(表头在第 1 行;000165 复测列序,无课件收集列(课件经列表「课件」入口维护):
// - 「所属部门」(A 列)下拉=组织架构部门;「课程分类」(E 列)下拉=配置中心 // 所属部门 A/课程名称 B/讲师 C/课程权限 D/课程分类 E/类型 F/线上或线下 G/时长 H/
// course_category_dict 字典(缺省回退内置 6 类);「讲师」(H 列)下拉=员工档案 // 课程说明 I/适合人员备注 J):
// - 「所属部门」(A 列)下拉=组织架构部门;「课程名称」(B 列)下拉=课程管理既有
// 课程名(可直接填写新名称);「课程分类」(F 列)下拉=配置中心
// course_category_dict 字典(缺省回退内置 6 类);「讲师」(C 列)下拉=员工档案
// 人员姓名(非阻断式,可直接输入外部讲师姓名); // 人员姓名(非阻断式,可直接输入外部讲师姓名);
// - 「类型」(F 列)「线上或线下」(G 列)「课件收集」(J 列)内联列表下拉 // - 「类型」(F 列)「线上或线下」(G 列)内联列表下拉(必修课/选修课、线上/线下)。
// (必修课/选修课、线上/线下、已有课件/暂无课件)。
// //
// 全部下拉为非阻断式(ShowErrorMessage=false):下拉建议 + 可自由填写。 // 全部下拉为非阻断式(ShowErrorMessage=false):下拉建议 + 可自由填写。
// 基础文件不可解析(如旧 .xls 自定义版)时原样返回,不阻断下载。 // 基础文件不可解析(如旧 .xls 自定义版)时原样返回,不阻断下载。
@@ -478,8 +481,26 @@ func (s *trainingService) enrichCourseLibraryTemplate(ctx context.Context, tenan
empNames = append(empNames, name) empNames = append(empNames, name)
} }
} }
// 课程名称下拉(000165 复测):课程管理既有课程名去重(可下拉选择也可直接填写新名)
courseNames := []string{}
if courses, _, err := s.repo.ListCourseLibrary(ctx, tenantID, &interfaces.TrainingListQuery{
Page: 1, PageSize: courseLibMemberLimit,
}); err == nil {
seen := map[string]bool{}
for _, c := range courses {
if c == nil {
continue
}
name := strings.TrimSpace(c.Name)
if name == "" || seen[name] {
continue
}
seen[name] = true
courseNames = append(courseNames, name)
}
}
applyCourseLibraryDropdowns(f, sheet, deptNames, categories, empNames) applyCourseLibraryDropdowns(f, sheet, deptNames, courseNames, categories, empNames)
buf, err := f.WriteToBuffer() buf, err := f.WriteToBuffer()
if err != nil { if err != nil {
@@ -511,11 +532,13 @@ func (s *trainingService) courseCategoryOptions(ctx context.Context, tenantID ui
} }
// applyCourseLibraryDropdowns 课程管理模板下拉注入(纯 xlsx 操作,便于单测): // applyCourseLibraryDropdowns 课程管理模板下拉注入(纯 xlsx 操作,便于单测):
// 动态选项(部门/分类/讲师)写同表隐藏辅助列后以数据验证引用;固定选项 // 000165 复测列序,无课件收集列(所属部门 A/课程名称 B/讲师 C/课程权限 D/课程分类 E/
// (类型/线上或线下/课件收集)用内联列表;全部非阻断式,可选可自由填写。 // 类型 F/线上或线下 G/时长 H/课程说明 I/适合人员备注 J)。
func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, categories, empNames []string) { // 动态选项(部门/课程名称/分类/讲师)写同表隐藏辅助列后以数据验证引用;固定选项
// 先清目标列既有验证(兼容租户上传过带验证的自定义模板),避免叠加重复下拉 // (类型/线上或线下)用内联列表;全部非阻断式,可选可自由填写。
for _, col := range []string{"A", "E", "F", "G", "H", "J"} { func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, courseNames, categories, empNames []string) {
// 先清目标列既有验证(含旧布局落点,兼容租户上传过带验证的自定义模板),避免叠加重复下拉
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "J"} {
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1)) _ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1))
} }
// 动态选项 → 隐藏辅助列 → 数据验证下拉(取值/落点/prompt 同收集模板 applyList) // 动态选项 → 隐藏辅助列 → 数据验证下拉(取值/落点/prompt 同收集模板 applyList)
@@ -543,10 +566,13 @@ func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, cate
} }
applyList(courseLibOptColDept, "所属部门(组织架构)", deptNames, applyList(courseLibOptColDept, "所属部门(组织架构)", deptNames,
fmt.Sprintf("A2:A%d", courseLibTargetRows+1), "从下拉选择组织架构部门;导入后按部门名自动关联") fmt.Sprintf("A2:A%d", courseLibTargetRows+1), "从下拉选择组织架构部门;导入后按部门名自动关联")
// 课程名称下拉(000165 复测):课程管理既有课程名,可直接填写新名称(同名导入沿用既有条目口径与需求侧一致)
applyList(courseLibOptColName, "课程名称(课程管理)", courseNames,
fmt.Sprintf("B2:B%d", courseLibTargetRows+1), "可从下拉选择课程管理已有课程;新课程直接填写名称即可")
applyList(courseLibOptColCat, "课程分类(配置)", categories, applyList(courseLibOptColCat, "课程分类(配置)", categories,
fmt.Sprintf("E2:E%d", courseLibTargetRows+1), "从下拉选择配置中心「课程分类」;分类之外可直接填写,导入后保存为自定义分类") fmt.Sprintf("E2:E%d", courseLibTargetRows+1), "从下拉选择配置中心「课程分类」;分类之外可直接填写,导入后保存为自定义分类")
applyList(courseLibOptColLect, "讲师(员工档案)", empNames, applyList(courseLibOptColLect, "讲师(员工档案)", empNames,
fmt.Sprintf("H2:H%d", courseLibTargetRows+1), "可从下拉选择系统员工,也可直接填写外部讲师姓名") fmt.Sprintf("C2:C%d", courseLibTargetRows+1), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
// 固定内联列表下拉(非阻断式可自由填写) // 固定内联列表下拉(非阻断式可自由填写)
inlineList := func(col, values, title, prompt string) { inlineList := func(col, values, title, prompt string) {
@@ -559,7 +585,6 @@ func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, cate
} }
inlineList("F", `"必修课,选修课"`, "类型", "从下拉选择必修课或选修课;留空默认必修课") inlineList("F", `"必修课,选修课"`, "类型", "从下拉选择必修课或选修课;留空默认必修课")
inlineList("G", `"线上,线下"`, "线上或线下", "从下拉选择线上或线下;留空默认线下") inlineList("G", `"线上,线下"`, "线上或线下", "从下拉选择线上或线下;留空默认线下")
inlineList("J", `"已有课件,暂无课件"`, "课件收集", "从下拉选择已有课件或暂无课件;也可直接填写课件名称")
} }
// SaveTrainingTemplate stores a tenant custom template (content-type validated upstream). // SaveTrainingTemplate stores a tenant custom template (content-type validated upstream).
@@ -8,16 +8,16 @@ import (
"github.com/xuri/excelize/v2" "github.com/xuri/excelize/v2"
) )
// 课程管理模板下拉注入(enrichCourseLibraryTemplate 的纯 xlsx 部分): // 课程管理模板下拉注入(enrichCourseLibraryTemplate 的纯 xlsx 部分,000165 复测列序,
// 部门/分类/讲师走隐藏辅助列,类型/线上或线下/课件收集内联列表,共 6 组下拉。 // 无课件收集列):部门/课程名称/分类/讲师走隐藏辅助列,类型/线上或线下内联列表,共 6 组下拉。
func TestApplyCourseLibraryDropdowns(t *testing.T) { func TestApplyCourseLibraryDropdowns(t *testing.T) {
f := excelize.NewFile() f := excelize.NewFile()
sheet := "课程管理" sheet := "课程管理"
f.SetSheetName("Sheet1", sheet) f.SetSheetName("Sheet1", sheet)
// 模拟内置资产表头(与 trainingtemplates.TestCourseLibraryDefaultAsset 同口径) // 模拟内置资产表头(与 trainingtemplates.TestCourseLibraryDefaultAsset 同口径)
for i, h := range []string{ for i, h := range []string{
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类", "所属部门", "课程名称", "讲师", "课程权限", "课程分类",
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集", "类型(必修课或选修课)", "线上或线下", "时长(学时)", "课程说明", "适合人员备注",
} { } {
cell, _ := excelize.CoordinatesToCellName(i+1, 1) cell, _ := excelize.CoordinatesToCellName(i+1, 1)
require.NoError(t, f.SetCellValue(sheet, cell, h)) require.NoError(t, f.SetCellValue(sheet, cell, h))
@@ -25,6 +25,7 @@ func TestApplyCourseLibraryDropdowns(t *testing.T) {
applyCourseLibraryDropdowns(f, sheet, applyCourseLibraryDropdowns(f, sheet,
[]string{"财务部", "技术部"}, []string{"财务部", "技术部"},
[]string{"员工手册培训", "保密意识培训"},
[]string{"专业技能类", "通用技能类"}, []string{"专业技能类", "通用技能类"},
[]string{"何莲", "王睿喆", "陆彦彤"}) []string{"何莲", "王睿喆", "陆彦彤"})
@@ -34,12 +35,12 @@ func TestApplyCourseLibraryDropdowns(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer f2.Close() defer f2.Close()
// 6 组数据验证全部挂上(部门/分类/讲师/类型/线上或线下/课件收集) // 6 组数据验证全部挂上(部门/课程名称/分类/讲师/类型/线上或线下)
dvs, err := f2.GetDataValidations(sheet) dvs, err := f2.GetDataValidations(sheet)
require.NoError(t, err) require.NoError(t, err)
require.GreaterOrEqual(t, len(dvs), 6) require.GreaterOrEqual(t, len(dvs), 6)
// 隐藏辅助列取值:CA=部门 / CB=分类 / CC=讲师 // 隐藏辅助列取值:CA=部门 / CB=分类 / CC=讲师 / CD=课程名称
v, err := f2.GetCellValue(sheet, "CA2") v, err := f2.GetCellValue(sheet, "CA2")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "财务部", v) require.Equal(t, "财务部", v)
@@ -49,10 +50,13 @@ func TestApplyCourseLibraryDropdowns(t *testing.T) {
v, err = f2.GetCellValue(sheet, "CC2") v, err = f2.GetCellValue(sheet, "CC2")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "何莲", v) require.Equal(t, "何莲", v)
v, err = f2.GetCellValue(sheet, "CD2")
require.NoError(t, err)
require.Equal(t, "员工手册培训", v)
// 重复注入不叠加:清旧验证后再挂,总数保持 6 // 重复注入不叠加:清旧验证后再挂,总数保持 6
applyCourseLibraryDropdowns(f2, sheet, applyCourseLibraryDropdowns(f2, sheet,
[]string{"财务部"}, []string{"专业技能类"}, []string{"何莲"}) []string{"财务部"}, []string{"员工手册培训"}, []string{"专业技能类"}, []string{"何莲"})
buf2, err := f2.WriteToBuffer() buf2, err := f2.WriteToBuffer()
require.NoError(t, err) require.NoError(t, err)
f3, err := excelize.OpenReader(bytes.NewReader(buf2.Bytes())) f3, err := excelize.OpenReader(bytes.NewReader(buf2.Bytes()))
@@ -14,6 +14,9 @@ package service
import ( import (
"context" "context"
"net"
neturl "net/url"
"os"
"strings" "strings"
"time" "time"
@@ -65,9 +68,52 @@ func (s *trainingService) WecomCheckinAuthURL(ctx context.Context, token, redire
if redirectURI == "" { if redirectURI == "" {
return "", errors.NewBadRequestError("缺少回跳地址") return "", errors.NewBadRequestError("缺少回跳地址")
} }
if err := validateWecomRedirectHost(redirectURI); err != nil {
return "", err
}
return client.BuildOAuthAuthorizeURL(redirectURI, token), nil return client.BuildOAuthAuthorizeURL(redirectURI, token), nil
} }
// validateWecomRedirectHost 回跳域名预检:redirect_uri 指向本机/内网地址时,
// 企微侧必然报"redirect_uri需使用应用可信域名"。与其让学员在手机上看晦涩的
// 企微报错,不如在落地页请求时直接给出可行动的提示(培训签到页须从对外域名
// 打开,二维码里的地址才会是可信域名)。
// 可用环境变量 WECOM_CHECKIN_TRUSTED_DOMAINS 显式声明可信域名(逗号分隔,
// 如 kbt.well-trust.com,kb.well-trust.com),配置后按白名单精确匹配;
// 未配置时按启发式拦截本机/内网/伪域名,放行其余公网域名。
func validateWecomRedirectHost(redirectURI string) error {
const hint = "签到页需从企微可信域名环境打开后重新生成二维码(测试 https://kbt.well-trust.com / 正式 https://kb.well-trust.com),并在企微管理后台为该自建应用配置「网页授权及JS-SDK可信域名」"
u, err := neturl.Parse(redirectURI)
if err != nil || u.Hostname() == "" {
return errors.NewBadRequestError("回跳地址不合法," + hint)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
// 显式白名单优先:配置了可信域名清单则精确匹配。
if listed := strings.TrimSpace(os.Getenv("WECOM_CHECKIN_TRUSTED_DOMAINS")); listed != "" {
for _, d := range strings.Split(listed, ",") {
if host == strings.ToLower(strings.TrimSpace(d)) {
return nil
}
}
return errors.NewBadRequestError("回跳域名 "+host+" 不在企微可信域名白名单内,"+hint)
}
// 启发式:拦截必然不被企微信任的地址(本机/内网 IP/单标签/伪域名)。
if host == "localhost" || host == "127.0.0.1" || host == "::1" || !strings.Contains(host, ".") {
return errors.NewBadRequestError("回跳域名 "+host+" 不是对外域名,"+hint)
}
if ip := net.ParseIP(host); ip != nil && (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()) {
return errors.NewBadRequestError("回跳域名 "+host+" 是内网地址,"+hint)
}
for _, suffix := range []string{".local", ".lan", ".internal", ".localhost"} {
if strings.HasSuffix(host, suffix) {
return errors.NewBadRequestError("回跳域名 "+host+" 不是对外域名,"+hint)
}
}
return nil
}
// WecomCheckinSession implements interfaces.TrainingService. // WecomCheckinSession implements interfaces.TrainingService.
// POST /training/wecom/checkin-session {code, state} — 匿名入口:OAuth code 换 // POST /training/wecom/checkin-session {code, state} — 匿名入口:OAuth code 换
// 身份并签发平台会话(签到即自动登录),同时一次带回落地页数据。 // 身份并签发平台会话(签到即自动登录),同时一次带回落地页数据。
@@ -159,10 +205,12 @@ func (s *trainingService) resolveWecomSignCode(ctx context.Context, token string
} }
// buildWecomCheckinPage 组装落地页载荷:课程/场次摘要 + 当前成员名单/重复标记。 // buildWecomCheckinPage 组装落地页载荷:课程/场次摘要 + 当前成员名单/重复标记。
// member 可为 nil(匿名落地页,工号未输入):此时跳过姓名补齐与名单/重复标记,
// 仅返回课程信息与签到码有效期。
func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types.TrainingSignCode, member *types.TrainingMember, prevToken bool) (*types.WecomCheckinPage, error) { func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types.TrainingSignCode, member *types.TrainingMember, prevToken bool) (*types.WecomCheckinPage, error) {
// 姓名:档案 UserName 为联查字段,直查不回填;用平台账号显示名补齐, // 姓名:档案 UserName 为联查字段,直查不回填;用平台账号显示名补齐,
// 落地页「工号 + 姓名」确认行展示(免登链路学员核对身份用)。 // 落地页「工号 + 姓名」确认行展示(免登链路学员核对身份用)。
if s.users != nil && member.UserName == "" { if member != nil && s.users != nil && member.UserName == "" {
if u, uerr := s.users.GetUserByID(ctx, member.UserID); uerr == nil && u != nil { if u, uerr := s.users.GetUserByID(ctx, member.UserID); uerr == nil && u != nil {
if u.DisplayName != "" { if u.DisplayName != "" {
member.UserName = u.DisplayName member.UserName = u.DisplayName
@@ -215,18 +263,104 @@ func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types
CanSignToday: session.StartAt != nil && sameBeijingDay(time.Now(), *session.StartAt), CanSignToday: session.StartAt != nil && sameBeijingDay(time.Now(), *session.StartAt),
} }
// 名单/重复标记:前端提前渲染按钮态(置灰/已签到),提交时后端仍强校验兜底。 // 名单/重复标记:前端提前渲染按钮态(置灰/已签到),提交时后端仍强校验兜底。
if roster, rerr := s.repo.ListEnrollments(ctx, code.TenantID, session.ID); rerr == nil { // 匿名模式(member 为 nil,工号未输入)无从判定,交给提交时强校验。
for _, e := range roster { if member != nil {
if e.MemberID == member.ID { if roster, rerr := s.repo.ListEnrollments(ctx, code.TenantID, session.ID); rerr == nil {
page.InRoster = true for _, e := range roster {
break if e.MemberID == member.ID {
page.InRoster = true
break
}
}
}
if rec, rerr := s.repo.GetSignRecord(ctx, code.TenantID, session.ID, member.ID); rerr == nil && rec != nil {
page.AlreadySigned = true
}
}
return page, nil
}
// ---------------------------------------------------------------------------
// 工号扫码签到(2026-11-25 调整):企微可信域名未就绪期间的免登替代流程。
// 扫码 → 落地页(课程信息+倒计时)→ 手输工号 → 按签到规则校验 → 工号反查
// 档案 → 签发会话(自动登录)。OAuth 链路(上方两方法)保留为可信域名配置
// 就绪后的恢复通道,前端不再默认走 OAuth。
// ⚠️ 风险已与需求方确认:工号属半公开信息,存在被知悉他人者冒签的可能;
// 自动登录可用规则项 employee_checkin_autologin 关闭。
// ---------------------------------------------------------------------------
// WecomCheckinPageAnon implements interfaces.TrainingService.
// POST /training/wecom/checkin-page-anon {token, employee_no?} — 匿名落地页数据;
// employeeNo 非空且能反查到档案时,附带名单/重复标记与展示行(前端即时提示)。
func (s *trainingService) WecomCheckinPageAnon(ctx context.Context, token, employeeNo string) (*types.WecomCheckinPage, error) {
code, prev, err := s.resolveWecomSignCode(ctx, strings.TrimSpace(token))
if err != nil {
return nil, err
}
var member *types.TrainingMember
if empNo := strings.TrimSpace(employeeNo); empNo != "" {
if m, merr := s.repo.GetMemberByEmployeeNo(ctx, code.TenantID, empNo); merr == nil && m != nil {
member = m
}
}
return s.buildWecomCheckinPage(ctx, code, member, prev)
}
// WecomCheckinByEmployee implements interfaces.TrainingService.
// POST /training/wecom/checkin-by-employee — 工号扫码签到:
// 签到码(token/轮换宽限)→ 工号反查档案 → 复用 Checkin 规则引擎(当天性/
// 名单硬拒/围栏/迟到/重复/nonce 防重放)→ 按规则开关签发会话(自动登录)。
func (s *trainingService) WecomCheckinByEmployee(ctx context.Context, token, employeeNo string, lat, lng float64, nonce string, clientTS int64) (*types.WecomCheckinByEmployee, error) {
token = strings.TrimSpace(token)
employeeNo = strings.TrimSpace(employeeNo)
if token == "" {
return nil, errors.NewBadRequestError("签到码无效,请重新扫码")
}
if employeeNo == "" {
return nil, errors.NewBadRequestError("请先输入工号")
}
code, prev, err := s.resolveWecomSignCode(ctx, token)
if err != nil {
return nil, err
}
member, err := s.repo.GetMemberByEmployeeNo(ctx, code.TenantID, employeeNo)
if err != nil || member == nil {
return nil, errors.NewNotFoundError("工号 " + employeeNo + " 不在培训档案中,请核对后重试或联系人事")
}
// 复用 Checkin 规则引擎:工号严格链路(employee_no 非空)当天性/名单硬拒/
// nonce/时钟偏差全部生效;档案由工号反查而来,工号一致性天然成立。
record, err := s.Checkin(ctx, code.TenantID, member.UserID, &types.CheckinInput{
Token: token,
Lat: lat,
Lng: lng,
Channel: "wecom_scan",
EmployeeNo: employeeNo,
Nonce: strings.TrimSpace(nonce),
ClientTS: clientTS,
})
if err != nil {
return nil, err
}
resp := &types.WecomCheckinByEmployee{Record: record}
page, err := s.buildWecomCheckinPage(ctx, code, member, prev)
if err != nil {
// 签到已成功,课程摘要构建失败不应吞掉结果:返回空页面载荷。
logger.Warnf(ctx, "wecom checkin: build page after employee checkin failed: %v", err)
page = &types.WecomCheckinPage{CourseID: "", SignExpireAt: code.ExpireAt}
}
resp.WecomCheckinPage = *page
// 自动登录(默认开):签发与 /auth/login 同构的会话;规则项可关,签发失败
// 不吞签到结果(best-effort,前端停留在成功页)。
if s.ruleFloat(ctx, code.TenantID, types.RuleKeySignPolicy, "employee_checkin_autologin", 1) > 0 && s.users != nil {
if user, uerr := s.users.GetUserByID(ctx, member.UserID); uerr == nil && user != nil {
if login, lerr := s.users.SessionResponseForUser(ctx, user); lerr == nil {
resp.LoginResponse = *login
} else {
logger.Warnf(ctx, "wecom checkin: issue session failed for user %s: %v", member.UserID, lerr)
} }
} }
} }
if rec, rerr := s.repo.GetSignRecord(ctx, code.TenantID, session.ID, member.ID); rerr == nil && rec != nil { return resp, nil
page.AlreadySigned = true
}
return page, nil
} }
// sameBeijingDay 判断两个时刻是否同一「北京时间」自然日(签到当天性校验统一 // sameBeijingDay 判断两个时刻是否同一「北京时间」自然日(签到当天性校验统一
+61 -59
View File
@@ -573,25 +573,19 @@ func (s *userService) finishOIDCLogin(
return nil, errors.New("OIDC provider did not return email") return nil, errors.New("OIDC provider did not return email")
} }
user, err := s.userRepo.GetUserByEmail(ctx, userInfo.Email) // 身份判定只看工号:username(工号)精确命中即认回老账号,邮箱不同
if err != nil && !isUserLookupNotFound(err) { // 不另开户;email 仅作工号未命中时的兜底匹配。见 resolveOIDCLoginUser。
return nil, fmt.Errorf("failed to query user by email: %w", err) user, err := s.resolveOIDCLoginUser(ctx, userInfo)
if err != nil {
return nil, err
} }
isNewUser := false isNewUser := false
if isUserLookupNotFound(err) || user == nil { if user == nil {
// 老账号自愈:占位邮箱曾按 sub(可能是长 UUID)合成,规则已改为 user, err = s.provisionOIDCUser(ctx, userInfo, provisioning)
// 工号优先。同一 Casdoor 用户下次登录时按 email 查不到,会落到 if err != nil {
// 这里——先按 username(工号)找回老账号,把它改成新短邮箱,避免 return nil, err
// 重复开户。仅当命中账号确属 OIDC 开户且现邮箱是同域占位邮箱时
// 才收编。
user = s.adoptOIDCUserByUsername(ctx, userInfo)
if user == nil {
user, err = s.provisionOIDCUser(ctx, userInfo, provisioning)
if err != nil {
return nil, err
}
isNewUser = true
} }
isNewUser = true
} }
// 姓名随登录刷新:IdP 侧改名后下一次登录生效(失败仅告警)。 // 姓名随登录刷新:IdP 侧改名后下一次登录生效(失败仅告警)。
@@ -2188,57 +2182,65 @@ func (s *userService) provisionOIDCUser(
return user, nil return user, nil
} }
// adoptOIDCUserByUsername 收编按旧规则开户的 OIDC 老账号。占位邮箱曾按 // resolveOIDCLoginUser 以工号为唯一身份键解析 SSO 登录对应的本地账号:
// sub(可能是长 UUID)合成;规则改为工号优先后,同一 Casdoor 用户下次 // 工号相同即同一人,邮箱不参与身份判定(员工改邮箱 / 测试 IdP 随意填写
// 登录按 email 查不到,这里按 username(工号)找回老账号并改写为短邮箱, // 邮箱,都不允许分裂出 "26040006-1" 式重复账号——OIDC 首登自动开户撞上
// 避免重复开户。收编条件全部满足才生效: // 已占用工号后会顺延 -1/-2 后缀)。解析顺序:
// 1. username 精确命中本地账号且账号活跃; // 1. username(工号)精确命中 → 认回,并把 IdP 邮箱同步为账号属性
// 2. 该账号是 OIDC 开户(OidcOnlyLogin); // (syncAdoptedOIDCEmail)。停用账号同样命中:交由调用方的停用检查
// 3. 现邮箱是同兜底域的占位邮箱; // 拒绝登录,避免停用员工绕道拿到 -1 新号;
// 4. 新邮箱(本次登录刚按新规则合成,查询未命中)必然未被占用。 // 2. email 精确命中 → 认回(工号 claim 异常 / 历史账号 username 非工号
// // 时的兜底,不改动该账号);
// 返回 nil 表示无可收编账号,调用方按新用户正常开户。失败仅告警,不阻塞登录。 // 3. 都未命中 → 返回 nil,调用方按新用户自动开户。
func (s *userService) adoptOIDCUserByUsername(ctx context.Context, info *types.OIDCUserInfo) *types.User { func (s *userService) resolveOIDCLoginUser(ctx context.Context, info *types.OIDCUserInfo) (*types.User, error) {
if s.config == nil || s.config.OIDCAuth == nil || s.userRepo == nil { if s.userRepo == nil {
return nil return nil, nil
} }
fallbackDomain := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s.config.OIDCAuth.EmailFallbackDomain), "@")) if candidate := sanitizeUsernameCandidate(info.Username); candidate != "" {
if fallbackDomain == "" { user, err := s.userRepo.GetUserByUsername(ctx, candidate)
return nil if err != nil && !isUserLookupNotFound(err) {
return nil, fmt.Errorf("failed to query user by username: %w", err)
}
if user != nil {
s.syncAdoptedOIDCEmail(ctx, user, info)
return user, nil
}
} }
if strings.Contains(info.Email, "@") && user, err := s.userRepo.GetUserByEmail(ctx, info.Email)
!strings.HasSuffix(strings.ToLower(info.Email), "@"+fallbackDomain) { if err != nil && !isUserLookupNotFound(err) {
// IdP 返回了真实邮箱,不涉及占位邮箱改写。 return nil, fmt.Errorf("failed to query user by email: %w", err)
return nil
} }
candidate := sanitizeUsernameCandidate(info.Username) if !isUserLookupNotFound(err) && user != nil {
if candidate == "" { return user, nil
return nil
} }
existing, err := s.userRepo.GetUserByUsername(ctx, candidate) return nil, nil
if err != nil || existing == nil || !existing.IsActive { }
return nil
// syncAdoptedOIDCEmail 工号收编后把 IdP 邮箱同步为账号属性(身份已由工号
// 锁定,邮箱只跟随 IdP)。唯一例外:IdP 侧是兜底域合成的占位邮箱而本地是
// 真实邮箱时不覆盖,避免真实邮箱被占位值冲掉。best-effort:失败仅告警,
// 不阻塞登录(下次登录重试)。
func (s *userService) syncAdoptedOIDCEmail(ctx context.Context, user *types.User, info *types.OIDCUserInfo) {
if user == nil || info.Email == "" || info.Email == user.Email {
return
} }
if existing.Preferences.OidcOnlyLogin == nil || !*existing.Preferences.OidcOnlyLogin { fallbackDomain := ""
return nil if s.config != nil && s.config.OIDCAuth != nil {
fallbackDomain = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s.config.OIDCAuth.EmailFallbackDomain), "@"))
} }
if !strings.HasSuffix(strings.ToLower(existing.Email), "@"+fallbackDomain) { idpIsPlaceholder := fallbackDomain != "" &&
return nil strings.HasSuffix(strings.ToLower(info.Email), "@"+fallbackDomain)
localIsPlaceholder := fallbackDomain != "" &&
strings.HasSuffix(strings.ToLower(user.Email), "@"+fallbackDomain)
if idpIsPlaceholder && !localIsPlaceholder {
return
} }
if info.Email == "" || info.Email == existing.Email { user.Email = info.Email
// 没有需要改写的邮箱(或新邮箱恰好与现值一致)。 if err := s.userRepo.UpdateUser(ctx, user); err != nil {
return existing logger.Warnf(ctx, "OIDC adopted-account email sync failed for user %s: %v", user.ID, err)
return
} }
existing.Email = info.Email logger.Infof(ctx, "OIDC adopted-account email synced: user %s email → %s", user.ID, user.Email)
if displayName := strings.TrimSpace(info.DisplayName); displayName != "" && existing.DisplayName == "" {
existing.DisplayName = displayName
}
if err := s.userRepo.UpdateUser(ctx, existing); err != nil {
logger.Warnf(ctx, "OIDC placeholder-email adoption failed for user %s: %v", existing.ID, err)
return nil
}
logger.Infof(ctx, "OIDC placeholder email rewritten: user %s email → %s", existing.ID, existing.Email)
return existing
} }
// refreshOIDCDisplayName 让姓名跟随 IdP:登录时若 claim 姓名变化则更新。 // refreshOIDCDisplayName 让姓名跟随 IdP:登录时若 claim 姓名变化则更新。
@@ -457,3 +457,230 @@ func TestFinishOIDCLoginRefreshesDisplayName(t *testing.T) {
t.Fatalf("UpdateUser calls = %d, want 1 (refresh persisted)", len(repo.updated)) t.Fatalf("UpdateUser calls = %d, want 1 (refresh persisted)", len(repo.updated))
} }
} }
// Regression for the 192-environment duplicate: a roster-imported 工号 account
// (real email, NOT OIDC-marked) whose email prefix differs from the IdP email
// must be adopted on first SSO login — not split into a fresh 26040006-1.
func TestFinishOIDCLoginAdoptsImportedAccountWithSameDomainEmail(t *testing.T) {
imported := &types.User{
ID: "26040006",
Username: "26040006",
Email: "26040006@hxzh.com", // 导入开户的真实邮箱,前缀与 IdP 不同
TenantID: 6,
IsActive: true,
}
repo := &sharedSpaceUserRepo{
getUserByEmail: nil, // IdP 邮箱按 email 查未命中
byUsername: map[string]*types.User{"26040006": imported},
}
memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{
{UserID: "26040006", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive},
}}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "26040006",
Email: "sun.kai@hxzh.com", // IdP 真实邮箱,同域不同前缀
DisplayName: "孙凯",
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if !resp.Success || resp.User == nil || resp.User.ID != "26040006" {
t.Fatalf("expected imported account adoption, got resp=%+v", resp)
}
if resp.IsNewUser {
t.Fatal("adoption must not be reported as a new user (26040006-1 regression)")
}
if resp.User.Email != "sun.kai@hxzh.com" {
t.Fatalf("email not normalized to IdP value: %s", resp.User.Email)
}
if len(repo.updated) == 0 {
t.Fatal("adoption must persist the rewritten account")
}
}
// Regression for the second 192 duplicate (蔡国梅 / 22030265-1): the IdP email
// lives on a completely unrelated domain (12.com) while the local account holds
// the fallback-domain placeholder. 工号 match must win — identity is the
// employee number, email is just an attribute that follows the IdP.
func TestFinishOIDCLoginAdoptsAccountWithCompletelyDifferentEmailDomain(t *testing.T) {
local := &types.User{
ID: "22030265",
Username: "22030265",
Email: "22030265@casdoor.local", // 本地占位邮箱
TenantID: 6,
IsActive: true,
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"22030265": local},
}
memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{
{UserID: "22030265", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive},
}}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@12.com", // IdP 真实邮箱,与本地完全不同域
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if !resp.Success || resp.User == nil || resp.User.ID != "22030265" {
t.Fatalf("expected adoption by 工号, got resp=%+v", resp)
}
if resp.IsNewUser {
t.Fatal("same 工号 with different email must not create 22030265-1")
}
if resp.User.Email != "22030265@12.com" {
t.Fatalf("email attribute not synced from IdP: %s", resp.User.Email)
}
if len(repo.updated) == 0 {
t.Fatal("email sync must be persisted")
}
}
// 工号命中但账号已停用:认回停用账号并被登录守卫拒绝,绝不绕道新建 -1 号
// (停用员工重新拿到可用账号比拒绝登录严重得多)。
func TestFinishOIDCLoginAdoptedInactiveAccountIsDisabled(t *testing.T) {
local := &types.User{
ID: "22030265",
Username: "22030265",
Email: "22030265@casdoor.local",
TenantID: 6,
IsActive: false,
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"22030265": local},
}
memberSvc := &sharedSpaceMemberSvc{}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@12.com",
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if resp.Success {
t.Fatal("disabled account must not log in")
}
if resp.Message != "Account is disabled" {
t.Fatalf("message = %q, want disabled", resp.Message)
}
if resp.IsNewUser {
t.Fatal("disabled account must not be re-provisioned as a fresh -1 account")
}
if len(memberSvc.adds) != 0 {
t.Fatalf("disabled account must not join any space: %+v", memberSvc.adds)
}
}
// 工号未命中(历史账号 username 不是工号)时回退按 email 命中,不另开户。
func TestFinishOIDCLoginFallsBackToEmailMatchWhenUsernameMisses(t *testing.T) {
legacy := &types.User{
ID: "legacy-zhangsan",
Username: "zhangsan", // 与工号 claim 不同
Email: "22030265@casdoor.local",
TenantID: 6,
IsActive: true,
}
repo := &sharedSpaceUserRepo{getUserByEmail: legacy}
memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{
{UserID: "legacy-zhangsan", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive},
}}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@casdoor.local",
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if !resp.Success || resp.User == nil || resp.User.ID != "legacy-zhangsan" {
t.Fatalf("expected email fallback match, got resp=%+v", resp)
}
if resp.IsNewUser {
t.Fatal("email fallback match must not create a new user")
}
if len(repo.updated) != 0 {
t.Fatalf("email-path match must not rewrite the account, got %+v", repo.updated)
}
}
func TestSyncAdoptedOIDCEmail(t *testing.T) {
mk := func(localEmail string) (*sharedSpaceUserRepo, *types.User) {
user := &types.User{ID: "22030265", Username: "22030265", Email: localEmail, IsActive: true}
repo := &sharedSpaceUserRepo{byUsername: map[string]*types.User{"22030265": user}}
return repo, user
}
svcWithCfg := func(repo *sharedSpaceUserRepo) *userService {
return &userService{userRepo: repo, config: oidcTestConfig()} // 兜底域 casdoor.local
}
t.Run("IdP placeholder never clobbers local real email", func(t *testing.T) {
repo, user := mk("zhang.san@hxzh.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@casdoor.local",
})
if user.Email != "zhang.san@hxzh.com" || len(repo.updated) != 0 {
t.Fatalf("real email clobbered: email=%s updated=%v", user.Email, repo.updated)
}
})
t.Run("IdP real email replaces local placeholder", func(t *testing.T) {
repo, user := mk("22030265@casdoor.local")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if user.Email != "22030265@12.com" || len(repo.updated) != 1 {
t.Fatalf("email not synced: email=%s updated=%v", user.Email, repo.updated)
}
})
t.Run("IdP real email replaces local real email", func(t *testing.T) {
repo, user := mk("old@hxzh.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "new@hxzh.com",
})
if user.Email != "new@hxzh.com" || len(repo.updated) != 1 {
t.Fatalf("email rename not synced: email=%s updated=%v", user.Email, repo.updated)
}
})
t.Run("same email writes nothing", func(t *testing.T) {
repo, user := mk("22030265@12.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if len(repo.updated) != 0 {
t.Fatalf("unexpected writes: %+v", repo.updated)
}
})
t.Run("no fallback domain config still syncs", func(t *testing.T) {
repo, user := mk("22030265@casdoor.local")
svc := &userService{userRepo: repo} // config 为 nil
svc.syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if user.Email != "22030265@12.com" || len(repo.updated) != 1 {
t.Fatalf("email not synced without fallback domain: email=%s updated=%v", user.Email, repo.updated)
}
})
}
@@ -405,9 +405,10 @@ func TestResolveOIDCUserInfo_VerifiedIDTokenUsedWhenUserinfoFails(t *testing.T)
} }
} }
// 工号式 IdP(邮箱选填):id_token 无 email claim 时,配置了兜底域则用已验签 // 工号式 IdP(邮箱选填):id_token 无 email claim 时,配置了兜底域则合成
// 的 sub 合成稳定占位邮箱,工号(name claim)继续作为 username。 // 稳定占位邮箱。合成 local part 工号(username claim)优先、sub 仅在
func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromSub(t *testing.T) { // username 为空时回落——工号比 Casdoor 可能的长 UUID sub 更短更稳定。
func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromUsername(t *testing.T) {
withOIDCSSRFWhitelist(t, "127.0.0.1") withOIDCSSRFWhitelist(t, "127.0.0.1")
key, err := rsa.GenerateKey(rand.Reader, 2048) key, err := rsa.GenerateKey(rand.Reader, 2048)
@@ -430,8 +431,8 @@ func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromSub(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("resolveOIDCUserInfo: %v", err) t.Fatalf("resolveOIDCUserInfo: %v", err)
} }
if info.Email != "built-in_10001@casdoor.local" { if info.Email != "10001@casdoor.local" {
t.Fatalf("email = %q, want synthesized from sub", info.Email) t.Fatalf("email = %q, want synthesized from 工号 username", info.Email)
} }
if info.Username != "10001" { if info.Username != "10001" {
t.Fatalf("username = %q, want 工号 from name claim", info.Username) t.Fatalf("username = %q, want 工号 from name claim", info.Username)
@@ -63,8 +63,9 @@ func TestCourseLibraryDefaultAsset(t *testing.T) {
rows, err := f.GetRows("课程管理") rows, err := f.GetRows("课程管理")
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, rows) require.NotEmpty(t, rows)
// 000165 复测列序:所属部门回第一列,无课件收集列(课件经列表「课件」入口维护)
require.Equal(t, []string{ require.Equal(t, []string{
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类", "所属部门", "课程名称", "讲师", "课程权限", "课程分类",
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集", "类型(必修课或选修课)", "线上或线下", "时长(学时)", "课程说明", "适合人员备注",
}, rows[0]) }, rows[0])
} }
+20
View File
@@ -582,6 +582,12 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
c.Error(err) c.Error(err)
return return
} }
// 企业培训系统默认库(课件/题库)仅超级管理员可查看,防止绕过列表过滤
// 直连详情接口。普通用户的课件/题库读写走培训业务接口(服务端同步)。
if kb.IsTrainingDefaultKB() && !types.IsSystemAdminFromContext(c.Request.Context()) {
c.Error(apperrors.NewForbiddenError("企业培训系统知识库仅超级管理员可查看"))
return
}
// Fill counts (knowledge_count, chunk_count, is_processing) so hover/detail shows correct numbers // Fill counts (knowledge_count, chunk_count, is_processing) so hover/detail shows correct numbers
if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil { if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil {
logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr) logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr)
@@ -660,6 +666,20 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
return return
} }
// 企业培训系统默认库(课件/题库)仅超级管理员可见:普通用户走业务模块
// (课程上传/题库导入)由服务端同步,无需在知识库列表直接浏览这两个库。
// 列表计数(@提及/智能体编辑器的知识库选择同源)随本过滤一并收口。
if !types.IsSystemAdminFromContext(ctx) {
filtered := make([]*types.KnowledgeBase, 0, len(kbs))
for _, kb := range kbs {
if kb.IsTrainingDefaultKB() {
continue
}
filtered = append(filtered, kb)
}
kbs = filtered
}
// Optional creator filter — drives the [All | Mine | Others] segmented // Optional creator filter — drives the [All | Mine | Others] segmented
// control on the list page. We filter in-process rather than pushing // control on the list page. We filter in-process rather than pushing
// down into SQL because the tenant-bounded KB list is small (typically // down into SQL because the tenant-bounded KB list is small (typically
+93 -13
View File
@@ -145,6 +145,23 @@ func (h *Handler) requireRoles(c *gin.Context, allowed ...string) (ok bool) {
return false return false
} }
// callerIsSuperAdmin 超级管理员判定:持有「超级管理员」职称角色(super_admin,
// 配置中心可配、组织架构「设置角色」可分配)或空间 Owner 兜底;空间 Admin 不放行。
// 已确认需求/已审核课程/已发布计划这类终态数据的删除仅对超级管理员开放,其余
// 角色仍按原状态规则拦截,前端删除按钮同口径仅超级管理员可见。
func (h *Handler) callerIsSuperAdmin(c *gin.Context) bool {
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
callerRole == types.TenantRoleOwner {
return true
}
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil || member == nil {
return false
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
return types.HasTrainingRole(roles, types.TrainingRoleSuperAdmin)
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 数据范围:课程/计划类列表按调用方职称角色收窄(权限模型 §数据范围) // 数据范围:课程/计划类列表按调用方职称角色收窄(权限模型 §数据范围)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -584,7 +601,9 @@ func (h *Handler) SaveDemand(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand}) c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
} }
// DeleteDemand DELETE /training/demands/:id — 删除未确认需求。 // DeleteDemand DELETE /training/demands/:id — 删除未确认需求;已确认需求仅
// 超级管理员(职称角色 super_admin/空间 Owner 兜底)可删(前端行内删除按钮
// 同口径仅超级管理员可见)。超级管理员删除时不再要求提报人/管理角色身份。
func (h *Handler) DeleteDemand(c *gin.Context) { func (h *Handler) DeleteDemand(c *gin.Context) {
ctx := c.Request.Context() ctx := c.Request.Context()
demand, err := h.svc.GetDemand(ctx, callerTenantID(c), c.Param("id")) demand, err := h.svc.GetDemand(ctx, callerTenantID(c), c.Param("id"))
@@ -592,15 +611,16 @@ func (h *Handler) DeleteDemand(c *gin.Context) {
_ = c.Error(err) _ = c.Error(err)
return return
} }
if demand.Status == types.TrainingDemandConfirmed { bySuperAdmin := h.callerIsSuperAdmin(c)
_ = c.Error(errors.NewBadRequestError("已确认的需求不可删除")) if demand.Status == types.TrainingDemandConfirmed && !bySuperAdmin {
_ = c.Error(errors.NewBadRequestError("已确认的需求不可删除,仅超级管理员可删除"))
return return
} }
if !h.callerCanMutateDemand(c, demand.SubmitterID) { if !bySuperAdmin && !h.callerCanMutateDemand(c, demand.SubmitterID) {
_ = c.Error(errors.NewForbiddenError("仅提报人或培训管理角色可删除该需求")) _ = c.Error(errors.NewForbiddenError("仅提报人或培训管理角色可删除该需求"))
return return
} }
if err := h.svc.DeleteDemand(ctx, callerTenantID(c), c.Param("id")); err != nil { if err := h.svc.DeleteDemand(ctx, callerTenantID(c), c.Param("id"), bySuperAdmin); err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
@@ -971,7 +991,7 @@ func (h *Handler) notifyDemandVerify(ctx context.Context, tenantID uint64, deman
} }
title := fmt.Sprintf("【年度培训需求核验】%d年度 %s 培训需求待核验", year, name) title := fmt.Sprintf("【年度培训需求核验】%d年度 %s 培训需求待核验", year, name)
content := fmt.Sprintf( content := fmt.Sprintf(
"%s 新导入 %d 条年度培训需求(课程:%s)。请登录 AIDO → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。", "%s 新导入 %d 条年度培训需求(课程:%s)。请登录和信智汇学院 → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。",
name, len(courses), strings.Join(courses, "、"), name, len(courses), strings.Join(courses, "、"),
) )
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year), "") n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year), "")
@@ -1007,7 +1027,7 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
} }
title := fmt.Sprintf("【培训计划维护】%s 已确认转入月培训计划", demand.CourseName) title := fmt.Sprintf("【培训计划维护】%s 已确认转入月培训计划", demand.CourseName)
content := fmt.Sprintf( content := fmt.Sprintf(
"%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:AIDO → 企业培训 → 月培训计划。", "%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:和信智汇学院 → 企业培训 → 月培训计划。",
demand.Year, demand.CourseName, demand.Year, demand.CourseName,
) )
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID, ""); err != nil { if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID, ""); err != nil {
@@ -1065,9 +1085,12 @@ func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint
category, suitable := trimSpace(d.Category), trimSpace(d.PostScope) category, suitable := trimSpace(d.Category), trimSpace(d.PostScope)
// 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止 // 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止
// 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。 // 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。
// 适合人员备注(000165):需求「适合人员」变更同步到课程管理备注字段,
// 与存量 suitable_members 口径一并比较(老数据备注为空时首改会触发回写)。
changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) || changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) ||
(category != "" && item.Category != category) || (category != "" && item.Category != category) ||
(suitable != "" && item.SuitableMembers != suitable) (suitable != "" && item.SuitableMembers != suitable) ||
(suitable != "" && item.PostScope != suitable)
if !changed { if !changed {
continue continue
} }
@@ -1081,6 +1104,7 @@ func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint
} }
if suitable != "" { if suitable != "" {
updated.SuitableMembers = suitable updated.SuitableMembers = suitable
updated.PostScope = suitable
} }
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil { if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync demand course info to course library", err) logger.Error(ctx, "Failed to sync demand course info to course library", err)
@@ -1373,13 +1397,16 @@ func (h *Handler) PublishCourse(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": published}) c.JSON(http.StatusOK, gin.H{"success": true, "data": published})
} }
// DeleteCourse DELETE /training/courses/:id // DeleteCourse DELETE /training/courses/:id — 已发布计划仅超级管理员(职称角色
// super_admin/空间 Owner 兜底)可删,其余状态仍为人事/课长(服务层同口径兜底
// 校验);超级管理员删除时不要求人事/课长身份。
func (h *Handler) DeleteCourse(c *gin.Context) { func (h *Handler) DeleteCourse(c *gin.Context) {
ctx := c.Request.Context() ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) { bySuperAdmin := h.callerIsSuperAdmin(c)
if !bySuperAdmin && !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return return
} }
if err := h.svc.DeleteCourse(ctx, callerTenantID(c), c.Param("id")); err != nil { if err := h.svc.DeleteCourse(ctx, callerTenantID(c), c.Param("id"), bySuperAdmin); err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
@@ -1855,7 +1882,8 @@ func (h *Handler) WecomCheckinAuth(c *gin.Context) {
} }
redirectURI := strings.TrimSpace(q.RedirectURI) redirectURI := strings.TrimSpace(q.RedirectURI)
if redirectURI == "" { if redirectURI == "" {
// 兜底:按请求 Host 还原落地页地址(反代透传 X-Forwarded-Proto)。 // 兜底:按请求 Host 还原落地页地址(独立手机端 H5 路由,反代透传
// X-Forwarded-Proto)。
scheme := "https" scheme := "https"
if c.Request.TLS == nil { if c.Request.TLS == nil {
if proto := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto")); proto != "" { if proto := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto")); proto != "" {
@@ -1864,7 +1892,7 @@ func (h *Handler) WecomCheckinAuth(c *gin.Context) {
scheme = "http" scheme = "http"
} }
} }
redirectURI = fmt.Sprintf("%s://%s/platform/training/checkin/%s", scheme, c.Request.Host, q.Token) redirectURI = fmt.Sprintf("%s://%s/m/training/checkin/%s", scheme, c.Request.Host, q.Token)
} }
url, err := h.svc.WecomCheckinAuthURL(c.Request.Context(), q.Token, redirectURI) url, err := h.svc.WecomCheckinAuthURL(c.Request.Context(), q.Token, redirectURI)
if err != nil { if err != nil {
@@ -1918,6 +1946,58 @@ func (h *Handler) WecomCheckinPage(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": page}) c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
} }
// WecomCheckinPageAnonRequest is the body of POST /training/wecom/checkin-page-anon.
// EmployeeNo 可选:非空时附带名单/重复标记(前端输入工号后即时提示)。
type WecomCheckinPageAnonRequest struct {
Token string `json:"token" binding:"required"`
EmployeeNo string `json:"employee_no"`
}
// WecomCheckinPageAnon POST /training/wecom/checkin-page-anon — 匿名落地页数据
// (课程信息/倒计时,工号未输入时不含成员信息)。2026-11-25 调整:工号主流程。
func (h *Handler) WecomCheckinPageAnon(c *gin.Context) {
var req WecomCheckinPageAnonRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("缺少签到码").WithDetails(err.Error()))
return
}
page, err := h.svc.WecomCheckinPageAnon(c.Request.Context(), req.Token, req.EmployeeNo)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
}
// WecomCheckinByEmployeeRequest is the body of POST /training/wecom/checkin-by-employee.
// Nonce 必带(需求规则 2:签到须提供随机时间戳防重放)。
type WecomCheckinByEmployeeRequest struct {
Token string `json:"token" binding:"required"`
EmployeeNo string `json:"employee_no" binding:"required"`
Nonce string `json:"nonce" binding:"required"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
ClientTS int64 `json:"client_ts"`
}
// WecomCheckinByEmployee POST /training/wecom/checkin-by-employee — 工号扫码
// 签到:按签到规则校验 + 工号反查档案 + 自动登录(签发会话随响应返回)。
// 匿名入口(noAuthAPI 白名单 + 签到专用限流),身份由「未过期签到码 token +
// 名单内工号」承载;冒签风险经需求方确认接受,自动登录可由规则项关闭。
func (h *Handler) WecomCheckinByEmployee(c *gin.Context) {
var req WecomCheckinByEmployeeRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不完整(签到码/工号/随机时间戳必填)").WithDetails(err.Error()))
return
}
resp, err := h.svc.WecomCheckinByEmployee(c.Request.Context(), req.Token, req.EmployeeNo, req.Lat, req.Lng, req.Nonce, req.ClientTS)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})
}
// ListSignRecords GET /training/sessions/:id/sign-records — 签到明细。 // ListSignRecords GET /training/sessions/:id/sign-records — 签到明细。
func (h *Handler) ListSignRecords(c *gin.Context) { func (h *Handler) ListSignRecords(c *gin.Context) {
items, err := h.svc.ListSignRecords(c.Request.Context(), callerTenantID(c), c.Param("id")) items, err := h.svc.ListSignRecords(c.Request.Context(), callerTenantID(c), c.Param("id"))
+115 -27
View File
@@ -29,9 +29,16 @@ type saveCourseLibraryRequest struct {
OwnerDeptID string `json:"owner_dept_id"` OwnerDeptID string `json:"owner_dept_id"`
// OwnerDeptName 所属部门名(导入兜底:前端未匹配到部门 id 时只传名, // OwnerDeptName 所属部门名(导入兜底:前端未匹配到部门 id 时只传名,
// 服务端按组织架构名册解析;与只读展示列 owner_dept_name 同名字段复用)。 // 服务端按组织架构名册解析;与只读展示列 owner_dept_name 同名字段复用)。
OwnerDeptName string `json:"owner_dept_name"` OwnerDeptName string `json:"owner_dept_name"`
Description string `json:"description"` Description string `json:"description"`
SuitableMembers string `json:"suitable_members"` SuitableMembers string `json:"suitable_members"`
// PermDeptIDs/PermUserIDs 课程权限(000163):可见部门/人员 id 列表(逗号
// 分隔);两者与 suitable_members 同时为空的存量课程沿用老口径。
PermDeptIDs string `json:"perm_dept_ids"`
PermUserIDs string `json:"perm_user_ids"`
// PostScope 适合人员备注(000165):自由文本只做展示,不参与权限过滤;
// 承接年/月培训计划的适合人员信息,并支持用户自定义录入。
PostScope string `json:"post_scope"`
Category string `json:"category"` Category string `json:"category"`
Type string `json:"type"` Type string `json:"type"`
Mode string `json:"mode"` Mode string `json:"mode"`
@@ -52,6 +59,9 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
OwnerDeptName: req.OwnerDeptName, OwnerDeptName: req.OwnerDeptName,
Description: req.Description, Description: req.Description,
SuitableMembers: req.SuitableMembers, SuitableMembers: req.SuitableMembers,
PermDeptIDs: req.PermDeptIDs,
PermUserIDs: req.PermUserIDs,
PostScope: req.PostScope,
Category: req.Category, Category: req.Category,
Type: req.Type, Type: req.Type,
Mode: req.Mode, Mode: req.Mode,
@@ -66,16 +76,21 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。 // ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅 // 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。 // 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方 // scope=catalog(000160)为学员目录口径:已发布 + 课程权限覆盖调用方
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护 // (000163:perm 部门/人员 id 命中;存量课程沿用适合人员老口径),不按维护
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。 // 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
// scope=plan(000163)创建月度计划选课口径:已下线课程不再可选;课程权限
// 覆盖调用方(人事作为培训管理员不受权限收窄,课程创建人/讲师放行);
// 纯学员/无维护角色调用方保持原数据范围,不放大数据可见性。
func (h *Handler) ListCourseLibrary(c *gin.Context) { func (h *Handler) ListCourseLibrary(c *gin.Context) {
q := listQueryFromRequest(c) q := listQueryFromRequest(c)
if q.Scope == "catalog" { if q.Scope == "catalog" {
q.CatalogOnly = true q.CatalogOnly = true
// 调用方部门(id+名)用于适合人员匹配;无培训档案的调用方两个字段 // 课程权限匹配身份(000163):调用方部门(id+名)+用户 id;无培训档案
// 留空(仅见「全部」与未设置适合人员的课程),不阻断目录查询。 // 的调用方部门字段留空(仅见「全部」与未设置权限的课程),不阻断目录。
q.PermUserID = callerUserID(c)
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil { if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID q.CatalogDeptID = member.DeptID
} }
if q.CatalogDeptID != "" { if q.CatalogDeptID != "" {
@@ -88,8 +103,57 @@ func (h *Handler) ListCourseLibrary(c *gin.Context) {
} }
} }
} }
} else if q.Scope == "plan" {
// scope=plan(000163)创建月度计划选课口径:月培训计划维护角色(人事/课长/
// 经理/讲师)可选全部部门的课程,不再按本部门收窄;纯学员/无维护角色
// 调用方保持原数据范围,不放大数据可见性。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
q.DeptID, q.RelatedUserID = "", ""
// 已下线课程不能再被计划选用(存量计划行不受影响)。
q.ExcludeOffline = true
// 课程权限收窄(000163):人事(培训管理员)不受限;课长/经理/讲师仅可
// 选择权限覆盖本人部门/本人(或本人创建/授课)的课程。
if !h.callerHasTrainingRole(c, types.TrainingRoleHR) {
q.PermFilter = true
q.PermIncludeCreator = true
q.PermUserID = callerUserID(c)
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
}
} else { } else {
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c) q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
// 课程权限收窄(000163):课程管理页对无维护角色的调用方(讲师/学员
// 「与我相关」口径)叠加课程权限过滤;维护角色(人事/课长/经理)保持
// 全量管理可见性 —— 审核按所属部门授权,不能被权限选择挡住。
if q.RelatedUserID != "" {
q.PermFilter = true
q.PermIncludeCreator = true
q.PermUserID = q.RelatedUserID
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
}
} }
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q) items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q)
if err != nil { if err != nil {
@@ -99,6 +163,17 @@ func (h *Handler) ListCourseLibrary(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}}) c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
} }
// callerHasTrainingRole 调用方是否具备指定培训角色(roles 已按权限组展开,
// 经理经课长继承自动命中)。
func (h *Handler) callerHasTrainingRole(c *gin.Context, want types.TrainingRole) bool {
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil || member == nil {
return false
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
return types.HasTrainingRole(roles, want)
}
// SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。 // SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。
// 维护角色限人事/课长/讲师;无维护角色的用户兜底仅可编辑「与我相关」课程 // 维护角色限人事/课长/讲师;无维护角色的用户兜底仅可编辑「与我相关」课程
// (本人创建或本人授课,不可新增,000157)。 // (本人创建或本人授课,不可新增,000157)。
@@ -138,17 +213,23 @@ func (h *Handler) canEditRelatedLibraryCourse(c *gin.Context, id string) bool {
} }
// DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除 // DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除
// (000157:仅本部门课长/经理,仅待核验状态;人事/学员/空间管理员无删除权限)。 // (000157:仅本部门课长/经理,仅待审核状态;人事/学员/空间管理员无删除权限。
// 超级管理员[职称角色 super_admin/空间 Owner 兜底]放开终态:已审核/已发布
// 课程与跨部门均可删,且不要求课长/经理身份)。
func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) { func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) { bySuperAdmin := h.callerIsSuperAdmin(c)
return deptID := ""
if !bySuperAdmin {
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) {
return
}
var ok bool
if deptID, ok = h.callerVerifyDeptScope(c); !ok {
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可删除课程"))
return
}
} }
deptID, ok := h.callerVerifyDeptScope(c) if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id"), deptID, bySuperAdmin); err != nil {
if !ok {
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可删除课程"))
return
}
if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id"), deptID); err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
@@ -207,14 +288,15 @@ func (h *Handler) callerVerifyDeptScope(c *gin.Context) (deptID string, ok bool)
} }
// verifyCourseLibraryRequest is the body of POST /training/course-library/verify // verifyCourseLibraryRequest is the body of POST /training/course-library/verify
// (单个/批量核验共用,ids 长度 1 即单条)。 // (单个/批量审核共用,ids 长度 1 即单条)。
type verifyCourseLibraryRequest struct { type verifyCourseLibraryRequest struct {
IDs []string `json:"ids" binding:"required,min=1"` IDs []string `json:"ids" binding:"required,min=1"`
} }
// VerifyCourseLibraryItems POST /training/course-library/verify — 课程条目核验 // VerifyCourseLibraryItems POST /training/course-library/verify — 课程条目审核
// (000157):仅本部门课长/经理可核验(人事/讲师/学员/空间管理员均无跨部门核验权), // (000163:核验升级为审核,审核通过即自动发布):仅本部门课长/经理可审核
// 待核验 → 已确认;越权/已确认/不存在行跳过不阻断其余行。 // (人事/讲师/学员/空间管理员均无跨部门审核权),待审核 → 已确认 + 自动发布;
// 课程权限未设置整批拒绝;越权/已确认/不存在行跳过不阻断其余行。
func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) { func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) { if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) {
return return
@@ -226,15 +308,15 @@ func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) {
} }
deptID, ok := h.callerVerifyDeptScope(c) deptID, ok := h.callerVerifyDeptScope(c)
if !ok { if !ok {
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可核验课程")) _ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可审核课程"))
return return
} }
verified, skipped, err := h.svc.VerifyCourseLibraryItems(c.Request.Context(), callerTenantID(c), req.IDs, callerUserID(c), deptID) result, err := h.svc.VerifyCourseLibraryItems(c.Request.Context(), callerTenantID(c), req.IDs, callerUserID(c), deptID)
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"verified": verified, "skipped": skipped}}) c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
} }
// ImportCourseLibraryRequest is the body of POST /training/course-library/import // ImportCourseLibraryRequest is the body of POST /training/course-library/import
@@ -335,12 +417,18 @@ func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
} }
// RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove // RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove
// — 移除课程课件原始文件/知识库挂接(名称登记保留,课件变更即回待核验)。 // — 移除课件条目(000164 多课件:body 可选 {mid} 定位条目,缺省移除最新一条;
// 课件变更即回待审核)。
func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) { func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) { if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return return
} }
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c)) // mid 可选(body 缺省/非 JSON 均按移除最新一条兼容旧调用,绑定错误忽略)。
var req struct {
Mid string `json:"mid"`
}
_ = c.ShouldBindJSON(&req)
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), req.Mid, callerUserID(c))
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
@@ -349,9 +437,9 @@ func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
} }
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file — // CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
// 课件原始文件流(下载/在线预览)。 // 课件原始文件流(下载/在线预览;query 可选 mid 定位课件条目,缺省最新一条)。
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) { func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id")) rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"), c.Query("mid"))
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
+5
View File
@@ -69,6 +69,11 @@ var noAuthAPI = map[string][]string{
// 鉴权,路由级 IP 限流承担防滥用;checkin-page(登录态)不在此列。 // 鉴权,路由级 IP 限流承担防滥用;checkin-page(登录态)不在此列。
"/api/v1/training/wecom/checkin-auth": {"GET"}, "/api/v1/training/wecom/checkin-auth": {"GET"},
"/api/v1/training/wecom/checkin-session": {"POST"}, "/api/v1/training/wecom/checkin-session": {"POST"},
// 工号扫码签到(2026-11-25 调整,可信域名未就绪期间的免登替代主流程):
// 身份由「未过期签到码 token + 名单内工号」承载,nonce 防重放,
// 自动登录可由规则项 employee_checkin_autologin 关闭。
"/api/v1/training/wecom/checkin-page-anon": {"POST"},
"/api/v1/training/wecom/checkin-by-employee": {"POST"},
// IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request // IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request
// before GET to validate Content-Type / Content-Length when rendering // before GET to validate Content-Type / Content-Length when rendering
// image previews — both verbs must be allowed for image links to work. // image previews — both verbs must be allowed for image links to work.
+4
View File
@@ -31,6 +31,10 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// 共享一个出口 IP,共享 auth 限流(30/min)会整批 429。 // 共享一个出口 IP,共享 auth 限流(30/min)会整批 429。
r.GET("/training/wecom/checkin-auth", middleware.WecomCheckinRateLimit(), h.WecomCheckinAuth) r.GET("/training/wecom/checkin-auth", middleware.WecomCheckinRateLimit(), h.WecomCheckinAuth)
r.POST("/training/wecom/checkin-session", middleware.WecomCheckinRateLimit(), h.WecomCheckinSession) r.POST("/training/wecom/checkin-session", middleware.WecomCheckinRateLimit(), h.WecomCheckinSession)
// 工号扫码签到(2026-11-25 调整:可信域名未就绪期间的免登替代主流程):
// 匿名落地页数据 + 工号签到(规则校验 + 工号反查 + 自动登录),同一限流桶。
r.POST("/training/wecom/checkin-page-anon", middleware.WecomCheckinRateLimit(), h.WecomCheckinPageAnon)
r.POST("/training/wecom/checkin-by-employee", middleware.WecomCheckinRateLimit(), h.WecomCheckinByEmployee)
// TrainingTenantResolution(000160):培训域数据空间按员工档案归属解析 —— // TrainingTenantResolution(000160):培训域数据空间按员工档案归属解析 ——
// 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在 // 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在
// 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。 // 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。
+9 -7
View File
@@ -51,14 +51,16 @@ func GrantsProductDocs(agent *CustomAgent) bool {
return agent != nil && agent.IsBuiltin && agent.ID == BuiltinAcademyAssistantID return agent != nil && agent.IsBuiltin && agent.ID == BuiltinAcademyAssistantID
} }
// UsesWorkspaceModelFallback reports whether a built-in agent runs without // UsesWorkspaceModelFallback reports whether an agent may run without its own
// its own model_id and rerank_model_id. These agents are hidden from agent // model_id and rerank_model_id. Built-in agents are seeded from
// management, so a user cannot configure them; the run resolves the chat // config/builtin_agents.yaml with no model ids; the agent editor only
// model from its knowledge base or the system KnowledgeQA default, and the // pre-fills the workspace default into the form, so until the user saves once
// rerank model from the workspace. // the persisted config stays empty. Rather than blocking the first chat with
// "chat model is not configured", the run resolves the chat model from the
// agent's knowledge base or the system KnowledgeQA default, and the rerank
// model from the workspace.
func UsesWorkspaceModelFallback(agent *CustomAgent) bool { func UsesWorkspaceModelFallback(agent *CustomAgent) bool {
return agent != nil && agent.IsBuiltin && return agent != nil && agent.IsBuiltin
(agent.ID == BuiltinWikiFixerID || agent.ID == BuiltinAcademyAssistantID)
} }
// RunsInSharedKBWorkspace reports whether a built-in agent opened on one // RunsInSharedKBWorkspace reports whether a built-in agent opened on one
+60 -12
View File
@@ -10,6 +10,17 @@ import (
"academy/internal/types" "academy/internal/types"
) )
// CourseLibraryVerifyResult 课程审核结果(000163:审核即发布):Verified 实际
// 审核通过条数;Skipped 越权/已确认/不存在跳过条数;AutoPublished 审核通过且
// 已有课件、同步自动发布的条数;UnpublishedNames 审核通过但未上传课件、未自动
// 发布的课程名(需传课件后重新审核)。
type CourseLibraryVerifyResult struct {
Verified int64 `json:"verified"`
Skipped int64 `json:"skipped"`
AutoPublished int64 `json:"auto_published"`
UnpublishedNames []string `json:"unpublished"`
}
// TrainingListQuery 通用列表查询(分页 + 关键词 + 可选过滤维度)。 // TrainingListQuery 通用列表查询(分页 + 关键词 + 可选过滤维度)。
type TrainingListQuery struct { type TrainingListQuery struct {
Year int Year int
@@ -36,6 +47,19 @@ type TrainingListQuery struct {
CatalogOnly bool CatalogOnly bool
CatalogDeptID string CatalogDeptID string
CatalogDeptName string CatalogDeptName string
// 课程权限过滤(000163,handler 按视图口径注入):PermFilter 开启后,课程
// 权限两列(perm_dept_ids/perm_user_ids)非空的课程仅当调用方部门/用户命中
// 才可见;两列为空的存量课程沿用 suitable_members 口径(与 CatalogOnly 的
// 存量兜底一致)。PermDeptID/PermUserID 为调用方部门 id 与用户 id。
// PermIncludeCreator 计划选课等场景对课程创建人/讲师放行(本人维护的课程
// 不受权限选择限制)。
PermFilter bool
PermDeptID string
PermUserID string
PermIncludeCreator bool
// ExcludeOffline 计划选课口径(000163,scope=plan):已下线课程不再可选,
// 存量计划行(tr_courses)不受影响。
ExcludeOffline bool
} }
// TrainingRepository 培训域数据访问(按域分组的方法集合)。 // TrainingRepository 培训域数据访问(按域分组的方法集合)。
@@ -52,6 +76,9 @@ type TrainingRepository interface {
// GetMemberByWecomUserid 企微免登反查:按 org_employees.wecom_userid 定位 // GetMemberByWecomUserid 企微免登反查:按 org_employees.wecom_userid 定位
// 培训档案(扫码签到 code 换身份,2026-11 需求)。 // 培训档案(扫码签到 code 换身份,2026-11 需求)。
GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error) GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error)
// GetMemberByEmployeeNo 工号扫码签到反查(2026-11-25 调整):按工号定位培训
// 档案;同工号多行(历史导入)取最早建档行。
GetMemberByEmployeeNo(ctx context.Context, tenantID uint64, employeeNo string) (*types.TrainingMember, error)
// FindArchiveTenantID 跨租户定位用户最早在职员工档案(org_employees)的租户 // FindArchiveTenantID 跨租户定位用户最早在职员工档案(org_employees)的租户
// (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。 // (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。
FindArchiveTenantID(ctx context.Context, userID string) (uint64, error) FindArchiveTenantID(ctx context.Context, userID string) (uint64, error)
@@ -96,6 +123,9 @@ type TrainingRepository interface {
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ---- // ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
// ListCourseLibraryStatuses 批量取课程条目发布状态(000163:学习入口拦截
// 已下线课程;ids 为 library_course_id 集合,返回 id → publish_status)。
ListCourseLibraryStatuses(ctx context.Context, tenantID uint64, ids []string) (map[string]string, error)
// FindCourseLibraryByName 按课程名称精准查找课程条目(000158 需求侧课程自动匹配)。 // FindCourseLibraryByName 按课程名称精准查找课程条目(000158 需求侧课程自动匹配)。
FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error) FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error)
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
@@ -110,6 +140,9 @@ type TrainingRepository interface {
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error) ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
// FirstCourseSession 取课程最靠前的有效场次(发布校验授课时间/地点的场次
// 兜底,2026-11-26;无场次返回 nil,不视为错误)。
FirstCourseSession(ctx context.Context, tenantID uint64, courseID string) (*types.TrainingCourseSession, error)
CreateSession(ctx context.Context, session *types.TrainingCourseSession) error CreateSession(ctx context.Context, session *types.TrainingCourseSession) error
UpdateSession(ctx context.Context, session *types.TrainingCourseSession) error UpdateSession(ctx context.Context, session *types.TrainingCourseSession) error
@@ -303,7 +336,9 @@ type TrainingService interface {
// ImportDemands 批量导入需求;返回导入行与自动新增的待核验课程数(000158)。 // ImportDemands 批量导入需求;返回导入行与自动新增的待核验课程数(000158)。
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error)
ConfirmDemand(ctx context.Context, tenantID uint64, id string, updaterID string) (*types.TrainingDemand, error) ConfirmDemand(ctx context.Context, tenantID uint64, id string, updaterID string) (*types.TrainingDemand, error)
DeleteDemand(ctx context.Context, tenantID uint64, id string) error // DeleteDemand 删除需求;bySuperAdmin(超级管理员职称角色/空间 Owner 兜底)
// 时已确认需求同样可删,其余角色仅未确认需求。
DeleteDemand(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。 // ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error) ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error)
ListPosts(ctx context.Context, tenantID uint64) ([]string, error) ListPosts(ctx context.Context, tenantID uint64) ([]string, error)
@@ -323,7 +358,9 @@ type TrainingService interface {
ListCourses(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourse, int64, error) ListCourses(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourse, int64, error)
GetCourse(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourse, error) GetCourse(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourse, error)
SaveCourse(ctx context.Context, tenantID uint64, course *types.TrainingCourse, updaterID string) (*types.TrainingCourse, error) SaveCourse(ctx context.Context, tenantID uint64, course *types.TrainingCourse, updaterID string) (*types.TrainingCourse, error)
DeleteCourse(ctx context.Context, tenantID uint64, id string) error // DeleteCourse 删除培训计划;bySuperAdmin(超级管理员职称角色/空间 Owner 兜底)
// 时已发布计划同样可删,其余角色仅未发布计划。
DeleteCourse(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error
PublishCourse(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourse, error) PublishCourse(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourse, error)
// ListCourseChangeLogs 课程信息修改版本记录(每次保存一条,变更明细可回溯)。 // ListCourseChangeLogs 课程信息修改版本记录(每次保存一条,变更明细可回溯)。
ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error) ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error)
@@ -335,27 +372,31 @@ type TrainingService interface {
SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error)
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154)。 // SetCourseLibraryPublishStatus 课程条目发布/下线(000154)。
SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
// VerifyCourseLibraryItems 批量核验课程条目(000157,仅本部门课长/经理): // VerifyCourseLibraryItems 批量审核课程条目(000163:核验升级为审核,审核
// deptScope 为调用方所在部门(恒非空),仅核验所属部门匹配的条目。 // 通过即自动发布;仅本部门课长/经理):deptScope 为调用方所在部门(恒非空),
VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (verified int64, skipped int64, err error) // 仅审核所属部门匹配的条目;课程权限未设置的条目整批拒绝(审核前置)。
VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (*CourseLibraryVerifyResult, error)
// GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。 // GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
// DeleteCourseLibraryItem 软删课程条目(仅待核验状态可删;deptScope 非空时 // DeleteCourseLibraryItem 软删课程条目(仅待审核状态可删;deptScope 非空时
// 校验所属部门匹配,000157 仅课长/经理限本部门)。 // 校验所属部门匹配,000157 仅课长/经理限本部门;bySuperAdmin 超级管理员
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string) error // 职称角色/空间 Owner 兜底时已审核/已发布课程与跨部门均放行)。
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string, bySuperAdmin bool) error
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后按行提交)。 // ImportCourseLibraryItems 批量导入(前端解析 Excel 后按行提交)。
ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error)
// ExportCourseLibrary 导出 Excel(excelize;ids 空 = 全量)。 // ExportCourseLibrary 导出 Excel(excelize;ids 空 = 全量)。
ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (filename string, data []byte, err error) ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (filename string, data []byte, err error)
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key)。 // UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key)。
UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error) UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error)
// GetCourseLibraryMaterialFile 流式取回课件原始文件。 // GetCourseLibraryMaterialFile 流式取回课件原始文件(000164:mid 定位条目,
GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error) // 空 = 最新一条)。
GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id, mid string) (io.ReadCloser, string, error)
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择 // AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
// 已有文档作为课程课件(与上传同步同口径)。 // 已有文档作为课程课件(与上传同步同口径)。
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
// RemoveCourseLibraryMaterial 移除课程课件(文件/知识库挂接清空,名称登记保留)。 // RemoveCourseLibraryMaterial 移除课件条目(000164 多课件:mid 定位,空 =
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) // 最新一条;文件/知识库挂接随条目移除,名称登记保留)。
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, mid, updaterID string) (*types.TrainingCourseLibrary, error)
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error) ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
@@ -397,6 +438,13 @@ type TrainingService interface {
WecomCheckinSession(ctx context.Context, code, state string) (*types.WecomCheckinSession, error) WecomCheckinSession(ctx context.Context, code, state string) (*types.WecomCheckinSession, error)
// WecomCheckinPage 已登录用户(PC 自测)取落地页数据。 // WecomCheckinPage 已登录用户(PC 自测)取落地页数据。
WecomCheckinPage(ctx context.Context, tenantID uint64, userID, token string) (*types.WecomCheckinPage, error) WecomCheckinPage(ctx context.Context, tenantID uint64, userID, token string) (*types.WecomCheckinPage, error)
// ---- 工号扫码签到(2026-11-25 调整:可信域名未就绪期间的免登替代) ----
// WecomCheckinPageAnon 匿名取落地页数据(课程信息/倒计时);employeeNo 非空时
// 附带回名单/重复标记与档案展示行(前端输入工号后即时提示)。
WecomCheckinPageAnon(ctx context.Context, token, employeeNo string) (*types.WecomCheckinPage, error)
// WecomCheckinByEmployee 工号扫码签到:按签到规则校验 + 工号反查档案 +
// 签发会话(自动登录,employee_checkin_autologin 开关控制)。
WecomCheckinByEmployee(ctx context.Context, token, employeeNo string, lat, lng float64, nonce string, clientTS int64) (*types.WecomCheckinByEmployee, error)
// ---- 培训佐证文件(签到照/培训视频) ---- // ---- 培训佐证文件(签到照/培训视频) ----
// UploadSessionEvidence 上传线下课佐证:签到照/培训视频按 file_key 落对象存储。 // UploadSessionEvidence 上传线下课佐证:签到照/培训视频按 file_key 落对象存储。
+124 -5
View File
@@ -30,6 +30,10 @@ const (
// TrainingRoleManager 经理(课长全部权限 + 审批决策 + 管理驾驶舱 + 讲师结算)。 // TrainingRoleManager 经理(课长全部权限 + 审批决策 + 管理驾驶舱 + 讲师结算)。
// 历史沿革:该角色前身是「高管(驾驶舱)」,key 保持 "exec" 不变以兼容存量数据。 // 历史沿革:该角色前身是「高管(驾驶舱)」,key 保持 "exec" 不变以兼容存量数据。
TrainingRoleManager TrainingRole = "exec" TrainingRoleManager TrainingRole = "exec"
// TrainingRoleSuperAdmin 超级管理员(终态数据删除权):已确认需求/已审核课程/
// 已发布计划这类终态数据仅该职称角色(及空间 Owner 兜底)可删,其余权限不做
// 放宽——删除权单独收敛,不随人事/课长默认携带。
TrainingRoleSuperAdmin TrainingRole = "super_admin"
) )
// legacyRoleClerk 部门文员(已移除的系统角色)。存量成员/自定义角色可能仍携带, // legacyRoleClerk 部门文员(已移除的系统角色)。存量成员/自定义角色可能仍携带,
@@ -66,12 +70,14 @@ func SystemTrainingRoles() []string {
return []string{ return []string{
TrainingRoleHR, TrainingRoleSupervisor, TrainingRoleHR, TrainingRoleSupervisor,
TrainingRoleLecturer, TrainingRoleManager, TrainingRoleLecturer, TrainingRoleManager,
TrainingRoleSuperAdmin,
} }
} }
// DefaultRoleDict 系统默认职称角色(与 defaultRuleSeed 的 role_dict 一致)。 // DefaultRoleDict 系统默认职称角色(与 defaultRuleSeed 的 role_dict 一致)。
// 角色体系 v2:学员(隐式)/课长/经理/人事/讲师;经理继承课长全部权限并叠加 // 角色体系 v2:学员(隐式)/课长/经理/人事/讲师;经理继承课长全部权限并叠加
// 审批决策、管理驾驶舱与讲师结算。 // 审批决策、管理驾驶舱与讲师结算。超级管理员不继承任何权限组,仅承载终态
// 数据(已确认需求/已审核课程/已发布计划)的删除权。
func DefaultRoleDict() []TrainingRoleDef { func DefaultRoleDict() []TrainingRoleDef {
return []TrainingRoleDef{ return []TrainingRoleDef{
{Key: TrainingRoleHR, Label: "人事", Short: "人事", System: true}, {Key: TrainingRoleHR, Label: "人事", Short: "人事", System: true},
@@ -79,6 +85,7 @@ func DefaultRoleDict() []TrainingRoleDef {
{Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true}, {Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true},
{Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true, {Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true,
Inherits: []string{TrainingRoleSupervisor}}, Inherits: []string{TrainingRoleSupervisor}},
{Key: TrainingRoleSuperAdmin, Label: "超级管理员", Short: "超管", System: true},
} }
} }
@@ -236,15 +243,22 @@ func hasString(list []string, want string) bool {
return false return false
} }
// NeedsRoleDictUpgrade 判断存量字典是否为 v1 口径(角色体系调整前): // NeedsRoleDictUpgrade 判断存量字典是否需要读时升级:
// v2 的硬标记是经理(exec)必须继承课长;凡不满足即视为 v1 需升级。 // - v1 口径:经理(exec)未继承课长(角色体系调整前的字典);
// - v2 口径但缺后续新增的系统角色(如超级管理员):同样需要补齐,
// 使存量租户无需迁移即可在配置中心看到并分配新角色。
func NeedsRoleDictUpgrade(dict []TrainingRoleDef) bool { func NeedsRoleDictUpgrade(dict []TrainingRoleDef) bool {
mgrFound := false
for _, r := range dict { for _, r := range dict {
if r.Key == TrainingRoleManager { if r.Key == TrainingRoleManager {
return !hasString(r.Inherits, TrainingRoleSupervisor) mgrFound = true
if !hasString(r.Inherits, TrainingRoleSupervisor) {
return true
}
} }
} }
return true // 字典缺经理角色(异常/极旧数据),同样需要补齐 // 缺经理(异常/极旧数据)或缺超级管理员,均视为需要升级
return !mgrFound || !hasString(RoleDictKeys(dict), TrainingRoleSuperAdmin)
} }
// UpgradeRoleDictV2 把 v1 存量字典升级为 v2(课长/经理/人事/讲师),幂等: // UpgradeRoleDictV2 把 v1 存量字典升级为 v2(课长/经理/人事/讲师),幂等:
@@ -545,6 +559,11 @@ type TrainingCourse struct {
Remark string `json:"remark" gorm:"type:text;default:''"` Remark string `json:"remark" gorm:"type:text;default:''"`
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」从课程管理选择后落此关联;可空)。 // LibraryCourseID 课程管理条目 id(月培训计划「计划名称」从课程管理选择后落此关联;可空)。
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"` LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
// LibraryPublishStatus 关联课程管理条目的发布状态(联查只读,不落库;
// offline 时学习页/学习入口按「该课程已下线」拦截)。
LibraryPublishStatus string `json:"library_publish_status" gorm:"-"`
// LibraryOffline 关联课程管理条目是否已下线(LibraryPublishStatus 衍生只读)。
LibraryOffline bool `json:"library_offline" gorm:"-"`
// PlanCode 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成,000153)。 // PlanCode 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成,000153)。
PlanCode string `json:"plan_code" gorm:"type:varchar(32);default:''"` PlanCode string `json:"plan_code" gorm:"type:varchar(32);default:''"`
// SourceDemandID 来源需求 id(经理确认自动转月度计划时回填,溯源用,000153)。 // SourceDemandID 来源需求 id(经理确认自动转月度计划时回填,溯源用,000153)。
@@ -580,6 +599,19 @@ const (
CourseLibraryVerifyConfirmed = "confirmed" CourseLibraryVerifyConfirmed = "confirmed"
) )
// CourseLibraryMaterial 课程管理课件条目(000164,多课件):一次上传/知识库挂接
// 追加一条,不再整体替换;Mid 为条目标识(移除/取流定位用),Name/Size 展示,
// FileKey/KnowledgeID 二选一(视频类仅存原始文件),Origin 标记来源(upload/kb)。
type CourseLibraryMaterial struct {
Mid string `json:"mid"`
Name string `json:"name"`
Size int64 `json:"size"`
FileKey string `json:"file_key"`
KnowledgeID string `json:"knowledge_id"`
Origin string `json:"origin"`
CreatedAt string `json:"created_at"`
}
// TrainingCourseLibrary 课程管理条目(课程资产主数据,000151)。 // TrainingCourseLibrary 课程管理条目(课程资产主数据,000151)。
// 月培训计划的「计划名称」从本表选择,选中计划创建时带 library_course_id 关联。 // 月培训计划的「计划名称」从本表选择,选中计划创建时带 library_course_id 关联。
type TrainingCourseLibrary struct { type TrainingCourseLibrary struct {
@@ -597,7 +629,19 @@ type TrainingCourseLibrary struct {
Description string `json:"description" gorm:"type:text;default:''"` Description string `json:"description" gorm:"type:text;default:''"`
// SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接 // SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接
// (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。 // (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
// 000163 起语义升级为「课程权限」展示文本(部门名+人员名),精确匹配走
// perm_dept_ids/perm_user_ids 两列,本列保留存量兼容与导出展示。
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"` SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"`
// PermDeptIDs 课程权限-部门(000163):逗号分隔的 org_depts.id,所选部门整体
// 可见该课程;与 perm_user_ids 同时为空时沿用 suitable_members 存量口径。
PermDeptIDs string `json:"perm_dept_ids" gorm:"type:varchar(512);default:''"`
// PermUserIDs 课程权限-人员(000163):逗号分隔的 users.id,所选人员可见该
// 课程;部门与该部门下人员互斥由前端保证(选了部门无需再选其下人员)。
PermUserIDs string `json:"perm_user_ids" gorm:"type:varchar(1024);default:''"`
// PostScope 适合人员备注(000165):自由文本只做展示,不参与课程权限过滤;
// 承接年/月培训计划(需求 post_scope/参加人员)过来的适合人员信息,并支持
// 用户在编辑弹窗自定义录入。
PostScope string `json:"post_scope" gorm:"type:varchar(512);default:''"`
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。 // Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
Category string `json:"category" gorm:"type:varchar(64);default:''"` Category string `json:"category" gorm:"type:varchar(64);default:''"`
// Type 类型(required 必修课/elective 选修课)。 // Type 类型(required 必修课/elective 选修课)。
@@ -618,7 +662,11 @@ type TrainingCourseLibrary struct {
// FileSize 课件文件字节数。 // FileSize 课件文件字节数。
FileSize int64 `json:"file_size" gorm:"default:0"` FileSize int64 `json:"file_size" gorm:"default:0"`
// KnowledgeID 课件同步知识库「企业培训(课件)」后的文档 id(视频类留空,000153,AI 出题依赖)。 // KnowledgeID 课件同步知识库「企业培训(课件)」后的文档 id(视频类留空,000153,AI 出题依赖)。
// 000164 起为「最新课件条目」镜像字段(多课件以 Materials 列表为准,主字段
// 恒指向最新一条,发布校验/AI 出题/学习抽屉等既有依赖口径不变)。
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"` KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
// Materials 课件列表(000164,多课件;JSON 数组落库):上传/挂接追加不替换。
Materials JSON `json:"materials" gorm:"type:jsonb;default:'[]'"`
// PublishStatus 发布状态(000154):draft 草稿/published 已发布/offline 已下线; // PublishStatus 发布状态(000154):draft 草稿/published 已发布/offline 已下线;
// 培训中心「和信课程」目录仅展示已发布且部门范围覆盖查看人的课程。 // 培训中心「和信课程」目录仅展示已发布且部门范围覆盖查看人的课程。
PublishStatus string `json:"publish_status" gorm:"type:varchar(16);default:'draft'"` PublishStatus string `json:"publish_status" gorm:"type:varchar(16);default:'draft'"`
@@ -649,6 +697,59 @@ type TrainingCourseLibrary struct {
// TableName pins the physical table name. // TableName pins the physical table name.
func (TrainingCourseLibrary) TableName() string { return "tr_course_library" } func (TrainingCourseLibrary) TableName() string { return "tr_course_library" }
// HasPermissionSet 是否已设置课程权限(000163,审核前置):perm 两列任一非空,
// 或存量 suitable_members 非空(含「全部」与自由文本)即视为已设置。
func (m TrainingCourseLibrary) HasPermissionSet() bool {
return strings.TrimSpace(m.PermDeptIDs) != "" ||
strings.TrimSpace(m.PermUserIDs) != "" ||
strings.TrimSpace(m.SuitableMembers) != ""
}
// HasCourseMaterial 是否已有课件(000164:materials 列表任一条,或旧版主字段
// 存量行兜底;名称登记不算,发布/自动发布前置)。
func (m TrainingCourseLibrary) HasCourseMaterial() bool {
return len(m.CourseMaterialList()) > 0 ||
strings.TrimSpace(m.FileKey) != "" ||
strings.TrimSpace(m.KnowledgeID) != ""
}
// CourseMaterialList 解析 materials 列(000164 多课件;空/坏 JSON 返回空列表)。
func (m TrainingCourseLibrary) CourseMaterialList() []CourseLibraryMaterial {
raw := strings.TrimSpace(string(m.Materials))
if raw == "" || raw == "null" || raw == "[]" {
return nil
}
var list []CourseLibraryMaterial
if err := json.Unmarshal(m.Materials, &list); err != nil {
return nil
}
return list
}
// PrimaryCourseMaterial 最新课件条目(主字段镜像对象;列表为空时由旧版主字段
// 构造兜底条目,迁移前的存量行在未跑 000164 回填时仍可展示/下载)。
func (m TrainingCourseLibrary) PrimaryCourseMaterial() *CourseLibraryMaterial {
list := m.CourseMaterialList()
if len(list) > 0 {
return &list[len(list)-1]
}
if m.FileKey == "" && m.KnowledgeID == "" {
return nil
}
origin := "upload"
if m.KnowledgeID != "" && m.FileKey == "" {
origin = "kb"
}
return &CourseLibraryMaterial{
Mid: "primary",
Name: m.FileName,
Size: m.FileSize,
FileKey: m.FileKey,
KnowledgeID: m.KnowledgeID,
Origin: origin,
}
}
// TrainingCourseStudyStats 课程维度的学习/考试参与成员聚合(课程管理列表状态列输入)。 // TrainingCourseStudyStats 课程维度的学习/考试参与成员聚合(课程管理列表状态列输入)。
type TrainingCourseStudyStats struct { type TrainingCourseStudyStats struct {
// SignedMembers 已签到成员(线下参与)。 // SignedMembers 已签到成员(线下参与)。
@@ -786,6 +887,14 @@ type TrainingSignRecord struct {
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"` DeletedAt *time.Time `json:"-" gorm:"index"`
// 联查只读展示字段(不落库,签到明细学员列由 ListSignRecords JOIN 提供):
// MemberName 真实姓名(users.display_name 优先,回退 username 工号);
// EmployeeNo/DeptName 来自 org_employees/org_depts 联查。
// 前端不再依赖名册全量反查(名册分页截断时学员列曾回退显示 member_id)。
MemberName string `json:"member_name" gorm:"->"`
EmployeeNo string `json:"employee_no" gorm:"->"`
DeptName string `json:"dept_name" gorm:"->"`
} }
// TableName pins the physical table name. // TableName pins the physical table name.
@@ -843,6 +952,16 @@ type WecomCheckinSession struct {
WecomCheckinPage WecomCheckinPage
} }
// WecomCheckinByEmployee 工号扫码签到响应(2026-11-25 调整:企微可信域名未就绪
// 期间的免登替代流程)——学员扫码进落地页手输工号,后端按签到规则校验并按工号
// 反查档案签发会话。Record 为签到流水;LoginResponse.Token 为空表示自动登录
// 关闭(employee_checkin_autologin=0)或签发失败,前端停留在成功页不跳转。
type WecomCheckinByEmployee struct {
LoginResponse
WecomCheckinPage
Record *TrainingSignRecord `json:"record"`
}
// 培训佐证文件类型:签到照 / 培训视频。 // 培训佐证文件类型:签到照 / 培训视频。
const ( const (
TrainingEvidenceSignPhoto = "sign_photo" TrainingEvidenceSignPhoto = "sign_photo"
+19 -8
View File
@@ -17,8 +17,8 @@ func marshalDict(t *testing.T, roles []TrainingRoleDef) []byte {
func TestDefaultRoleDict(t *testing.T) { func TestDefaultRoleDict(t *testing.T) {
dict := DefaultRoleDict() dict := DefaultRoleDict()
if len(dict) != 4 { if len(dict) != 5 {
t.Fatalf("default dict should have 4 system roles, got %d", len(dict)) t.Fatalf("default dict should have 5 system roles, got %d", len(dict))
} }
sysKeys := SystemTrainingRoles() sysKeys := SystemTrainingRoles()
for i, r := range dict { for i, r := range dict {
@@ -33,10 +33,15 @@ func TestDefaultRoleDict(t *testing.T) {
} }
} }
// 经理必须继承课长(经理权限 = 课长全部 + 审批决策) // 经理必须继承课长(经理权限 = 课长全部 + 审批决策)
mgr := dict[len(dict)-1] mgr := dict[3]
if mgr.Key != TrainingRoleManager || !hasString(mgr.Inherits, TrainingRoleSupervisor) { if mgr.Key != TrainingRoleManager || !hasString(mgr.Inherits, TrainingRoleSupervisor) {
t.Fatalf("manager should inherit supervisor, got %+v", mgr) t.Fatalf("manager should inherit supervisor, got %+v", mgr)
} }
// 超级管理员:纯删除权角色,不继承任何权限组
super := dict[len(dict)-1]
if super.Key != TrainingRoleSuperAdmin || len(super.Inherits) != 0 {
t.Fatalf("super admin should have no inherits, got %+v", super)
}
} }
func TestParseRoleDictValid(t *testing.T) { func TestParseRoleDictValid(t *testing.T) {
@@ -45,22 +50,23 @@ func TestParseRoleDictValid(t *testing.T) {
{Key: TrainingRoleSupervisor, Label: "课长", Short: "课长", System: true}, {Key: TrainingRoleSupervisor, Label: "课长", Short: "课长", System: true},
{Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true}, {Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true},
{Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true, Inherits: []string{"", TrainingRoleSupervisor}}, {Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true, Inherits: []string{"", TrainingRoleSupervisor}},
{Key: TrainingRoleSuperAdmin, Label: "超级管理员", Short: "超管", System: true},
{Key: "trainer_plus", Label: "资深讲师", Inherits: []string{TrainingRoleLecturer, TrainingRoleSupervisor}}, {Key: "trainer_plus", Label: "资深讲师", Inherits: []string{TrainingRoleLecturer, TrainingRoleSupervisor}},
}) })
dict, err := ParseRoleDict(raw) dict, err := ParseRoleDict(raw)
if err != nil { if err != nil {
t.Fatalf("valid dict rejected: %v", err) t.Fatalf("valid dict rejected: %v", err)
} }
if len(dict) != 5 { if len(dict) != 6 {
t.Fatalf("expect 5 roles, got %d", len(dict)) t.Fatalf("expect 6 roles, got %d", len(dict))
} }
last := dict[4] last := dict[5]
if len(last.Inherits) != 2 || last.Inherits[0] != TrainingRoleLecturer { if len(last.Inherits) != 2 || last.Inherits[0] != TrainingRoleLecturer {
t.Fatalf("inherits not preserved/cleaned: %v", last.Inherits) t.Fatalf("inherits not preserved/cleaned: %v", last.Inherits)
} }
// short 缺省回退 label // short 缺省回退 label
if dict[4].Short != "资深讲师" { if dict[5].Short != "资深讲师" {
t.Fatalf("short should fall back to label, got %q", dict[4].Short) t.Fatalf("short should fall back to label, got %q", dict[5].Short)
} }
// manager 的空 inherit 被清理,课长继承保留 // manager 的空 inherit 被清理,课长继承保留
if len(dict[3].Inherits) != 1 || dict[3].Inherits[0] != TrainingRoleSupervisor { if len(dict[3].Inherits) != 1 || dict[3].Inherits[0] != TrainingRoleSupervisor {
@@ -75,6 +81,7 @@ func TestParseRoleDictInvalid(t *testing.T) {
{Key: TrainingRoleSupervisor, Label: "课长", Short: "课长", System: true}, {Key: TrainingRoleSupervisor, Label: "课长", Short: "课长", System: true},
{Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true}, {Key: TrainingRoleLecturer, Label: "讲师", Short: "讲师", System: true},
{Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true, Inherits: []string{TrainingRoleSupervisor}}, {Key: TrainingRoleManager, Label: "经理", Short: "经理", System: true, Inherits: []string{TrainingRoleSupervisor}},
{Key: TrainingRoleSuperAdmin, Label: "超级管理员", Short: "超管", System: true},
} }
} }
cases := []struct { cases := []struct {
@@ -194,6 +201,10 @@ func TestNeedsRoleDictUpgrade(t *testing.T) {
if NeedsRoleDictUpgrade(DefaultRoleDict()) { if NeedsRoleDictUpgrade(DefaultRoleDict()) {
t.Fatal("v2 default dict should not need upgrade") t.Fatal("v2 default dict should not need upgrade")
} }
// v2 口径但缺 v2.1 增补的超级管理员:同样需要读时升级补齐(存量租户免迁移)
if !NeedsRoleDictUpgrade(DefaultRoleDict()[:4]) {
t.Fatal("v2 dict missing super_admin should need upgrade")
}
} }
func TestUpgradeRoleDictV2(t *testing.T) { func TestUpgradeRoleDictV2(t *testing.T) {
@@ -0,0 +1,3 @@
-- 000163 回滚:移除课程管理条目课程权限两列(回落 suitable_members 存量口径)。
ALTER TABLE tr_course_library DROP COLUMN IF EXISTS perm_dept_ids;
ALTER TABLE tr_course_library DROP COLUMN IF EXISTS perm_user_ids;
@@ -0,0 +1,19 @@
-- Migration: 000163_course_library_permission
-- 课程管理「课程权限」(测试反馈 2026-11-26):
-- perm_dept_ids:可见部门 id 列表(逗号分隔,org_depts.id);
-- perm_user_ids:可见人员 id 列表(逗号分隔,users.id)。
-- 课程权限 = 部门 + 人员混合选择,部门与该部门下人员互斥(前端保证);
-- 仅所选部门和人员可在月培训计划选课、课程管理、培训中心「和信课程」看到课程。
-- 两列为空时沿用存量 suitable_members 口径(「全部」/部门名/所属部门兜底),
-- 存量数据零迁移。全部 ADD COLUMN IF NOT EXISTS,迁移幂等可重放。
DO $$ BEGIN RAISE NOTICE '[Migration 000163] Adding tr_course_library permission columns...'; END $$;
ALTER TABLE tr_course_library
ADD COLUMN IF NOT EXISTS perm_dept_ids VARCHAR(512) NOT NULL DEFAULT '';
ALTER TABLE tr_course_library
ADD COLUMN IF NOT EXISTS perm_user_ids VARCHAR(1024) NOT NULL DEFAULT '';
COMMENT ON COLUMN tr_course_library.perm_dept_ids IS 'Course permission dept ids (comma-joined org_depts.id); empty = legacy suitable_members semantics';
COMMENT ON COLUMN tr_course_library.perm_user_ids IS 'Course permission user ids (comma-joined users.id); empty = legacy suitable_members semantics';
@@ -0,0 +1,3 @@
-- 000164 回滚:移除课程管理课件列表列(存量多课件中最新一条仍保留在
-- file_*/knowledge_id 主字段,回滚不丢最新课件)。
ALTER TABLE tr_course_library DROP COLUMN IF EXISTS materials;
@@ -0,0 +1,38 @@
-- Migration: 000164_course_library_multi_materials
-- 课程管理「课件管理」支持多课件(测试反馈 2026-11-26):tr_course_library 增加
-- materials JSONB 列(课件条目数组,一次上传/知识库挂接追加一条,不再整体替换)。
-- 条目结构:{mid,name,size,file_key,knowledge_id,origin,created_at}
-- 主字段镜像:file_key/file_name/file_size/knowledge_id 恒指向最新一条课件,
-- 发布校验/AI 出题/学习抽屉/月计划带出等既有依赖口径不变。
-- 存量回填:旧版单课件主字段迁移为一条课件条目(mid 用 md5 随机生成),迁移
-- 幂等可重放(仅 materials='[]' 且有课件的行)。
DO $$ BEGIN RAISE NOTICE '[Migration 000164] Adding tr_course_library materials column + legacy backfill...'; END $$;
ALTER TABLE tr_course_library
ADD COLUMN IF NOT EXISTS materials JSONB NOT NULL DEFAULT '[]';
UPDATE tr_course_library
SET materials = jsonb_build_array(jsonb_build_object(
'mid', md5(random()::text || clock_timestamp()::text),
'name', COALESCE(NULLIF(file_name, ''), NULLIF(material_name, ''), '课件'),
'size', file_size,
'file_key', COALESCE(file_key, ''),
'knowledge_id', COALESCE(knowledge_id, ''),
'origin', CASE WHEN COALESCE(knowledge_id, '') <> '' AND COALESCE(file_key, '') = '' THEN 'kb' ELSE 'upload' END,
'created_at', to_char(COALESCE(updated_at, now()) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')))
WHERE deleted_at IS NULL
AND materials = '[]'::jsonb
AND (COALESCE(file_key, '') <> '' OR COALESCE(knowledge_id, '') <> '');
-- 「审核即发布」存量回填(2026-11-26 复测):旧版本时代已审核确认且已有课件的
-- 课程,新流程已移除「发布」按钮(审核通过即自动发布),此批课程需补齐发布
-- 状态,否则将永远停留在「待发布」且无发布入口。
UPDATE tr_course_library
SET publish_status = 'published'
WHERE deleted_at IS NULL
AND verify_status = 'confirmed'
AND publish_status = 'draft'
AND (COALESCE(file_key, '') <> '' OR COALESCE(knowledge_id, '') <> '' OR materials <> '[]'::jsonb);
COMMENT ON COLUMN tr_course_library.materials IS 'Course library materials (000164 multi-courseware JSON array, append-only); primary file columns mirror the latest entry';
@@ -0,0 +1,4 @@
-- Migration: 000165_course_library_post_scope (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000165] Dropping tr_course_library post_scope column...'; END $$;
ALTER TABLE tr_course_library DROP COLUMN IF EXISTS post_scope;
@@ -0,0 +1,14 @@
-- Migration: 000165_course_library_post_scope
-- 课程管理新增「适合人员」备注字段(测试反馈 2026-11-26):
-- post_scope: 适合人员备注(自由文本,只做展示,不参与课程权限过滤),
-- 承接「年培训计划」「月培训计划」过来的适合人员/参加人员信息,并支持
-- 用户在课程管理编辑弹窗自定义录入。
-- 与 000163 课程权限列(perm_dept_ids/perm_user_ids/存量 suitable_members)互不干扰。
-- ADD COLUMN IF NOT EXISTS,迁移幂等可重放。
DO $$ BEGIN RAISE NOTICE '[Migration 000165] Adding tr_course_library post_scope column...'; END $$;
ALTER TABLE tr_course_library
ADD COLUMN IF NOT EXISTS post_scope VARCHAR(512) NOT NULL DEFAULT '';
COMMENT ON COLUMN tr_course_library.post_scope IS 'Suitable personnel remark (display-only free text carried over from annual/monthly training plans; not used for permission filtering)';
+43
View File
@@ -0,0 +1,43 @@
// 校验课程权限 SQL 常量括号配平与占位符数量(2026-11-26 复测根因定位辅助)
const fs = require('fs')
const src = fs.readFileSync('internal/application/repository/training_library.go', 'utf8')
const start = src.indexOf('const courseLibraryPermissionMatchSQL')
const end = src.indexOf('// courseLibraryPermissionCond 组装')
const block = src.slice(start, end)
const parts = []
let i = 0
while (true) {
const q1 = block.indexOf('"', i)
if (q1 < 0) break
let j = q1 + 1
let out = ''
while (j < block.length) {
if (block[j] === '\\') {
out += block[j + 1]
j += 2
continue
}
if (block[j] === '"') break
out += block[j]
j += 1
}
parts.push(out)
i = j + 1
}
const sql = parts.join('')
const opens = (sql.match(/\(/g) || []).length
const closes = (sql.match(/\)/g) || []).length
const qs = (sql.match(/\?/g) || []).length
console.log('opens=', opens, 'closes=', closes, 'placeholders=', qs, 'BALANCED=', opens === closes)
// 括号深度轨迹:定位未闭合位置(深度未回 0 即缺失右括号)
let depth = 0
for (let k = 0; k < sql.length; k++) {
if (sql[k] === '(') depth += 1
if (sql[k] === ')') depth -= 1
}
console.log('final depth =', depth, '(>0 表示缺少右括号)')
// 输出最后 120 个字符,便于人工核对末尾闭合
console.log('--- tail ---')
console.log(sql.slice(-120))
console.log('--- SQL ---')
console.log(sql)