diff --git a/docs/design/企微扫码签到免登-落地方案.md b/docs/design/企微扫码签到免登-落地方案.md new file mode 100644 index 0000000..3e8df2a --- /dev/null +++ b/docs/design/企微扫码签到免登-落地方案.md @@ -0,0 +1,244 @@ +# 企微扫码签到免登 · 落地方案 + +> 状态:方案评审阶段(未开发) +> 日期:2026-11-25 +> 涉及模块:企业培训-培训签到(`frontend/src/views/training`、`internal/application/service/training_course.go`) +> 关联文档:`docs/design/企业培训系统-Academy落地方案.md` §5.3 权限模型 + +## 0. 环境与域名规划 + +| 环境 | 对外访问地址 | 说明 | +|---|---|---| +| 测试 | `https://kbt.well-trust.com/` | 企微后台可信域名需含此域名;放归属校验文件 | +| 正式 | `https://kb.well-trust.com/` | 同上;生产扫码入口 | + +域名带来的方案简化: + +1. **HTTPS 已满足** —— HTML5 定位(Geolocation)可正常工作,定位围栏防作弊无障碍; +2. **二维码地址直接用 `window.location.origin`** —— 讲师 PC 与学员手机访问同一域名(测试环境生成 `kbt` 链接、正式生成 `kb` 链接,天然隔离),**不再需要新增"对外访问基础地址"配置项**(保留系统设置兜底项,防有人经内网地址访问,非必需); +3. **免登 redirect_uri 跟随二维码域名** —— 学员扫哪个环境的码,OAuth 回调就回哪个环境,无需环境判断逻辑。 + +## 1. 背景与目标 + +### 1.1 现状链路(已具备) + +| 环节 | 现状 | 位置 | +|---|---|---| +| 二维码内容 | `${window.location.origin}/platform/training/checkin/{token}` | `frontend/src/views/training/components/SignPanel.vue:249` | +| 落地页 | 进页自动取定位并提交签到 | `frontend/src/views/training/CheckinPage.vue` | +| 签到规则引擎 | token/过期/场次状态/名单/迟到/围栏/重复 全齐 | `internal/application/service/training_course.go:761` | +| 签到码存储 | `tr_sign_codes` 按 (tenant_id, session_id) 唯一,upsert 整行替换 | `internal/types/training.go:748`、`internal/application/repository/training_plan_course.go:754` | +| 企微凭据 | 租户 IM webhook 渠道存 corp_id/agent_secret/corp_agent_id(推送在用) | `internal/im/wecompush/client.go:26` | +| 身份绑定 | `org_employees.wecom_userid`(手动维护 + OA 同步两条链路) | `internal/router/routes_training.go:44-47` | +| 平台 JWT 签发 | 后端自签 access+refresh token | `/auth/login` → `userService.generateTokensForTenant`,`internal/application/service/user.go:1376` | + +### 1.2 现状断点(为什么企微扫一扫现在不能直接签到) + +1. **登录墙**:落地页路由挂 `requiresAuth: true`(`frontend/src/router/index.ts:192`),签到接口在 `g.Viewer()` 守卫后;企微内置浏览器无 localStorage JWT → 直接被踢登录页; +2. **自动登录缺位**:即使解决免登,签到后也无处签发平台会话。 + +### 1.3 调整后的需求(本方案范围) + +**逻辑**:员工企微扫码 → 直接进入签到页面 → 页面展示课程信息,点击「签到」按钮完成签到。 + +**规则**: +1. 校验是否培训当天签到,非当天友好提示; +2. 签到提交须携带员工工号 + 随机时间戳;超过二维码有效期须重新扫码; +3. 签到二维码每 5 分钟自动轮换一次,旧码即时作废,须重新扫码。 + +**补充**: +1. 签到页展示课程相关信息; +2. 展示签到倒计时,过期提示重新扫码; +3. 签到成功后提示,并**自动登录平台**、跳转该课程详情页。 + +## 2. 目标交互时序 + +``` +讲师PC(SignPanel) 学员手机(企微扫一扫) 后端 + │ 进入签到页即生成签到码 │ │ + │ 每5分钟自动轮换(旧码即时作废) │ │ + │───────────────────────────────▶│ 内置浏览器打开落地页(无登录态) │ + │ │ ① 静默免登: 跳企微OAuth(snsapi_base) │ + │ │ ◀─ 302 回落地页 ?code&state ──────────│ code→userid→wecom_userid反查→工号/姓名 + │ │ ② 展示: 课程信息卡片+倒计时+签到按钮 │ 同时签发平台JWT(access+refresh) → 自动登录完成 + │ │ ③ 学员点击「签到」→ 取定位 → 提交 ──────▶│ 当天校验/工号比对/时间戳防重放/围栏/迟到/重复 + │ │ ◀─ 签到结果 ──────────────────────────│ + │ │ ④ 提示成功 → 已有登录态 → 自动跳课程详情页 │ +``` + +要点: +- scope 用 `snsapi_base`,静默授权,学员侧零输入; +- 身份映射复用 `wecom_userid` 绑定,零新增数据; +- 签到规则复用现有 `Checkin()` 引擎,新规则为插入式增强; +- 非企微环境(PC/微信)扫码:展示"请使用企业微信扫一扫",不影响主流程。 + +## 3. 方案设计 + +### 3.1 二维码 5 分钟自动轮换(规则 3) + +**核心机制:复用现有 upsert 覆盖语义,旧码作废零开发。** + +| 项 | 设计 | 代码依据 | +|---|---|---| +| 轮换动作 | 重新生成 32 位 token + `UpsertSignCode` 覆盖唯一行 | `trainingNewToken()` `training_course.go:746`;`UpsertSignCode`(OnConflict DoUpdates) `training_plan_course.go:754` | +| 旧码作废 | 行被覆盖后 `GetSignCodeByToken(旧token)` 查无 → 现有 Checkin 直接报"签到码无效" | `training_plan_course.go:783` + `training_course.go:764` | +| 轮换判定 | `now - UpdatedAt ≥ rotation_sec(默认 300s)` 时轮换 | sign_policy 规则项(规则表机制已有,`ruleFloat` `training_course.go:799`) | +| 触发方式 | **后端惰性轮换为主**:`GET /sessions/:id/sign-code` 读时超窗自动轮换并返回新码;讲师页每 10s 轮询该接口,token 变化即重绘 | SignPanel 已有 `watch(signCode, buildSignQr)` 自动重绘(`SignPanel.vue:256`),补 `setInterval`(onUnmounted 清理) | +| 有效期模型 | 每轮 `expire_at = min(now + 5min, 场次总有效期)`;场次总有效期沿用 `start+4h / now+12h` | `training_course.go:722-727`;讲师页/学员页倒计时同口径 | + +**踩空保护(建议做,可配置关闭)**: +学员在第 4 分 50 秒扫码、点击时刚好轮换会直接失败。加单级历史:`tr_sign_codes` 增列 `prev_token / prev_expire_at`,轮换时旧 token 挪入 prev;Checkin 允许 prev token 在 `rotation_grace_sec(30s)` 宽限内签到。不做则严格按需求"作废须重扫"。 + +### 3.2 企微免登 + 自动登录(支撑需求补充 3) + +新增两个匿名接口(挂 noAuthAPI 白名单,参照 `TrainingTemplateSignedFilePath` 先例 `routes_training.go:22-26`): + +**① `GET /api/v1/training/wecom/checkin-auth?token=xxx`** +- 按 token 全局查码(repo 增加不带 tenant 条件的查询变体;`TrainingSignCode` 自带 `TenantID`,顺带解决匿名入口的租户解析); +- 从该租户 IM webhook 渠道读 corp_id/agent_id/secret(抽 `wecompush.TenantClient` 的凭据读取段共用,`wecompush/client.go:40-58`); +- 返回企微授权 URL: + + ``` + https://open.weixin.qq.com/connect/oauth2/authorize + ?appid={CORPID} + &redirect_uri=https%3A%2F%2F{当前环境域名}%2Fplatform%2Ftraining%2Fcheckin%2F{token} + &response_type=code + &scope=snsapi_base + &state={sign_token} + &agentid={AGENTID} + #wechat_redirect + ``` + + `redirect_uri` 直接取请求的 Host(kbt/kb 跟随二维码环境); +- 前端 `location.replace` 跳转(静默,学员无感)。 + +**② `POST /api/v1/training/wecom/checkin-session {code, state}`** +- 校验 `state` = 未过期签到码 token(防乱回调); +- `code → userid`(`GET /cgi-bin/auth/getuserinfo`,access_token 复用 `ProactiveClient` 的 gettoken+缓存,补 `GetUserInfo(code)` 方法,参照 `proactive_client.go:123` 的 gettoken); +- `userid → org_employees.wecom_userid` 反查用户(仿 `TenantWecomUserIDs` 查法,`wecompush/client.go:64`);查不到 → 报"未绑定企微账号,请联系人事在组织架构维护"; +- **自动登录关键步**:`userService.generateTokensForTenant(ctx, user, resolveLoginTenantID(...))` 签发标准 access+refresh token(`user.go:1376`),与 `/auth/login` 同构; + - ⚠️ 登录落点走**默认登录解析**,不强制指到培训档案空间——培训域跨空间已有 `TrainingTenantResolution` 兜底(`routes_training.go:30`),两者解耦,避免破坏"最近活跃租户"偏好逻辑(参考 commit 448fbcd); +- 返回: + + ```json + { + "token": "...", "refresh_token": "...", + "user": { "...": "平台用户" }, + "member": { "employee_no": "26040006", "name": "孙凯" }, + "course": { + "course_id": "...", "name": "新入职培训", + "lecturer_name": "…", "start_at": "…", "location": "…", + "status": "scheduled", "can_sign_today": true + }, + "sign": { "expire_at": "2026-11-25T14:32:00+08:00", "session_id": "..." } + } + ``` + +- 前端按 `/auth/login` 同构写入(`localStorage.academy_token` + auth store 持久化,`stores/auth.ts` 现有路径),`refreshAccessTokenShared` 刷新逻辑直接生效——**自动登录即完成**; +- 防滥用:按 IP 限流;code 由企微保证一次性,换不到 userid 即拒。 + +### 3.3 落地页重构 `CheckinPage.vue`(补充 1/2/3) + +现文件是"进页自动签到"(`CheckinPage.vue:110` 的 `onMounted(submit)` 移除),重构为五态状态机: + +| 态 | 内容 | +|---|---| +| `authing` | 企微 UA(含 `wxwork`)+ 无本地 JWT → 调 ① → 跳 OAuth → 带 code 回跳 → 调 ② | +| `ready` | **课程信息卡片**(课程名/讲师/上课时间/地点/场次状态,来自 ② 响应,不发额外请求);**工号+姓名确认行**;**倒计时进度条**(`expire_at - now`,秒级刷新,剩 60s 变红);**「点击签到」大按钮** | +| `submitting` | 点击签到 → HTML5 定位(沿用现 `locate()` 6 秒兜底,`CheckinPage.vue:68`)→ 调签到接口 | +| `success` | 签到结果(成功/迟到/待复核)→ "已自动登录,正在进入课程详情…" → `router.push('/platform/training/course/'+course_id)`(路由已存在 `router/index.ts:182`,此时有 JWT 直接通过) | +| `blocked` | 分支文案见 §7 | + +配套小改: +- 路由 `trainingCheckin` 去掉 `requiresAuth / requiresInit`(改页面自理),`router/index.ts:192`; +- 非企微环境:已登录(PC 讲师自测)直接进 `ready`;未登录展示"请使用企业微信扫一扫"; +- `api/training` 增封装:`getCheckinAuthUrl / checkinSession / checkin(增参)`。 + +### 3.4 签到规则增强 `Checkin()`(规则 1/2) + +在现有规则链(`token → 过期 → 场次状态 → 档案 → 名单 → 迟到 → 围栏 → 重复`,`training_course.go:761-824`)中插入: + +1. **当天校验**(过期校验后、迟到判定前):`session.StartAt != nil && !sameBeijingDay(now, *session.StartAt)` → 拆两种友好错误: + - 提前扫:"培训尚未开始,X月X日 XX:00 开课,当天再来签到"; + - 滞后:"本课程签到已结束"。 + - 时区固定 +8(不依赖服务器 TZ;前端 `fmtBeijingTime` 同口径)。 + - **双保险**:② 返回的 `can_sign_today` 已让页面提前置灰按钮,后端强校验兜底。 +2. **工号比对**:请求体新增 `employee_no`,后端与解析出的 `member.EmployeeNo` 严格比对,不一致拒绝(满足"签到需提供工号",防串号)。 +3. **随机时间戳(防重放)**:请求体新增 `nonce`(前端生成:`Date.now() + 随机段`)+ `client_ts`;后端校验 `|now - client_ts| ≤ clock_skew_sec(60s)`、nonce 未使用(查重);`tr_sign_records` 加 `nonce` 列留痕。与二维码有效期联动:token 过期仍由现有校验拦(`training_course.go:766`),前端倒计时归零即禁用按钮。 +4. handler 请求体扩展:`CheckinRequest`(`internal/handler/training/training.go:1783`)。 + +## 4. 接口变更清单 + +### 新增(匿名,挂 noAuthAPI 白名单) + +| 接口 | 说明 | +|---|---| +| `GET /api/v1/training/wecom/checkin-auth?token=` | 返回企微 OAuth 授权 URL | +| `POST /api/v1/training/wecom/checkin-session` | code 换身份 + 签发 JWT + 课程摘要(免登 & 自动登录一体) | +| `GET /WW_verify_{xxx}.txt` | 企微域名归属校验文件(noAuth 静态;两环境域名各一份) | + +### 修改 + +| 接口/文件 | 变更 | +|---|---| +| `POST /training/sign-records/checkin` | 请求体加 `employee_no / nonce / client_ts`;`Checkin()` 插入当天校验、工号比对、nonce 去重、(可选)prev_token 宽限 | +| `GET /training/sessions/:id/sign-code` | 惰性轮换:读时超 `rotation_sec` 自动轮换返回新码 | +| `frontend/src/views/training/components/SignPanel.vue` | 讲师页 10s 轮询 + 5 分钟轮换节奏展示(下次更新倒计时);二维码地址保持 origin(kbt/kb 随环境) | +| `frontend/src/views/training/CheckinPage.vue` | 五态状态机重构(§3.3) | +| `frontend/src/router/index.ts:192` | `trainingCheckin` 路由去 `requiresAuth/requiresInit` | +| `frontend/src/api/training/index.ts` | 增 `getCheckinAuthUrl / checkinSession`;`checkin` 增参(`index.ts:650`) | + +## 5. 数据与配置变更 + +**DB(量很小)** + +| 表 | 变更 | +|---|---| +| `tr_sign_codes` | `+ prev_token varchar(64)`、`+ prev_expire_at`(宽限方案,可选) | +| `tr_sign_records` | `+ nonce varchar(64)` | + +**规则配置**(sign_policy,沿用现有规则表机制,`rule-configs` 接口可配 `routes_training.go:186-188`): + +| 键 | 默认 | 说明 | +|---|---|---| +| `rotation_sec` | 300 | 二维码轮换窗口 | +| `rotation_grace_sec` | 30 | prev_token 宽限(0 = 严格作废) | +| `clock_skew_sec` | 60 | client_ts 时钟偏差容忍 | +| `same_day_check` | on | 培训当天校验开关 | + +## 6. 企微管理后台配置清单(一次性硬前置) + +| # | 配置项 | 内容 | 备注 | +|---|---|---|---| +| 1 | 网页授权及JS-SDK可信域名 | `kb.well-trust.com`、`kbt.well-trust.com` | 自建应用配置;**需确认 well-trust.com 已 ICP 备案**(企微后台强制校验) | +| 2 | 域名归属校验 | 下载 `WW_verify_xxx.txt` 部署到两域名根路径 | 部署在反代或前端 `public/`;两环境各配各的 | +| 3 | 企业可信IP | 服务器出口 IP | 2022-06 后调 gettoken/getuserinfo 强制;测试/正式环境各自的出口 IP | +| 4 | HTTPS | ✅ 已满足(kbt/kb 均为 https) | 定位功能前提,已具备 | + +## 7. 边界场景与文案 + +| 场景 | 页面表现 | +|---|---| +| 提前扫码(非当天) | 按钮置灰 + "培训尚未开始,X月X日 XX:00 开课,当天再来签到"(后端二次强校验兜底) | +| 倒计时归零 / 点击时已轮换 | "二维码已更新,请重新扫码" + 引导文案(页内唤起企微扫一扫需 JS-SDK,放 P2;一期提示退出重扫) | +| 重复扫码 | "您已签到,请勿重复扫码"(现有报错直出,`training_course.go:823`) | +| 名单外 | 照常落记录 → "已提交,待复核"(现有逻辑) | +| 未绑定 wecom_userid | "未绑定企微账号,请联系人事在组织架构维护" | +| 定位失败 / 围栏外 | 照常提交,标 `outside` 进复核(现有,不动) | +| 场次已取消/结束 | 现有拦截文案(`training_course.go:773`) | +| 微信(非企微)扫码 | "请使用企业微信『扫一扫』完成签到" | + +## 8. 实施分期 + +| 期 | 内容 | 量 | +|---|---|---| +| **P0 核心链路** | 免登两接口 + JWT 签发自动登录 + CheckinPage 五态重构 + Checkin 规则增强(当天/工号/nonce)+ 惰性轮换与讲师页轮询 | 3~4 天 | +| **P1 体验补全** | WW_verify 路由、规则配置项落地、prev_token 宽限、限流、文案打磨 | 1 天 | +| **P2 增强(按需)** | JS-SDK `wx.scanQRCode` 页内重扫、`wx.getLocation` 定位增强、开课推送消息带签到直达链接(复用 `training_notify` 推送链路) | 按需 | + +**测试环境验证路径**:先在企微后台配 `kbt.well-trust.com` 可信域名 + 校验文件 + 可信 IP → 测试环境走通全链路 → 再复制配置到 `kb`(正式)。 + +## 9. 待拍板事项 + +1. **宽限期**:严格按需求"轮换即作废",还是加 30s prev_token 宽限防"扫码即轮换"踩空?(建议加,`rotation_grace_sec` 可关) +2. **企微后台三项配置**(可信域名/校验文件/可信IP)需管理员先落地,`well-trust.com` 的 ICP 备案状态需确认——这是整个方案的开关,建议最先验证。 diff --git a/frontend/src/api/training/index.ts b/frontend/src/api/training/index.ts index 1e5b874..d9ab619 100644 --- a/frontend/src/api/training/index.ts +++ b/frontend/src/api/training/index.ts @@ -474,6 +474,8 @@ export interface TrainingLibraryCourse { creator_id?: string /** 创建人姓名(联查 users 只读;导入/新增时落 creator_id 后带出) */ creator_name?: string + /** 关联题库数(联查只读;列表「试题」有/无展示) */ + question_bank_count?: number created_at?: string updated_at?: string } @@ -526,6 +528,12 @@ export const attachCourseLibraryMaterialFromKb = (id: string, payload: { knowled export const downloadCourseLibraryMaterial = (id: string) => getDown(`${base}/course-library/${enc(id)}/material/file`) +/** 移除课件原始文件/知识库挂接(名称登记保留;课件变更即回待核验)。 */ +export const removeCourseLibraryMaterial = (id: string) => + post<{ success: boolean; data: TrainingLibraryCourse }>( + `${base}/course-library/${enc(id)}/material/remove`, + ) + export const listSessions = (query?: ListQuery) => get<{ success: boolean; data: TrainingCourseSession[] }>(`${base}/sessions`, { params: query }) diff --git a/frontend/src/test-utils/trainingMockApi.ts b/frontend/src/test-utils/trainingMockApi.ts index f98f8c7..374dfb6 100644 --- a/frontend/src/test-utils/trainingMockApi.ts +++ b/frontend/src/test-utils/trainingMockApi.ts @@ -165,9 +165,9 @@ export const TRAINING_MOCK = { // 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致) const COURSE_LIBRARY_MOCK = [ - { id: 'lib-1', code: 'CRS-0001', name: '新员工入职通识培训', owner_dept_id: 'dept-b', owner_dept_name: '技术部', description: '公司制度、企业文化与办公系统入门', suitable_members: '新入职员工', category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) }, - { id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) }, - { id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) }, + { 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-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-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) }, ] // 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####) @@ -313,6 +313,26 @@ export function resolveTrainingMock(method: string, url: string): { status: numb if (url.includes('/question-banks/') && url.includes('/questions')) { return ok({ id: `q-new-${Date.now()}`, seq_no: 0 }) } + // 课件管理抽屉:上传/知识库挂接/移除回显对应课程条目并模拟文件字段变更 + if (url.includes('/course-library/') && url.includes('/material/remove')) { + const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`)) + if (course) { + course.file_name = '' + course.file_size = 0 + course.knowledge_id = '' + course.verify_status = 'pending' + } + return ok(course || { id: `c-new-${Date.now()}` }) + } + if (url.includes('/course-library/') && url.includes('/material')) { + const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`)) + if (course) { + course.file_name = '预览课件.pdf' + course.file_size = 1024 * 820 + course.verify_status = 'pending' + } + return ok(course || { id: `c-new-${Date.now()}` }) + } 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 }) } diff --git a/frontend/src/views/training/components/CoursePanel.vue b/frontend/src/views/training/components/CoursePanel.vue index 72d8c1b..bf76bd5 100644 --- a/frontend/src/views/training/components/CoursePanel.vue +++ b/frontend/src/views/training/components/CoursePanel.vue @@ -98,6 +98,14 @@
选择后带出课程信息且不可修改,仅可调整下方授课安排;还没有课程?前往「课程管理」新增
+ + + + 线下(集中授课) + 线上(自主学习) + + @@ -202,8 +210,9 @@ - + + + + + 线下(集中授课) + 线上(自主学习) + + @@ -873,12 +889,12 @@ const form = ref({ description: '', }) -// 从课程管理选择课程:带出课程信息(类型/形式/讲师/学时/所属部门/说明)并锁定, -// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员) +// 从课程管理选择课程:带出课程信息(名称/类型/讲师/学时/所属部门/说明)并锁定, +// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员); +// 「形式」为计划侧独立字段(000162),不随所选课程带出,由表单自行选择 const onLibraryCourseChange = (libraryCourseId: unknown) => { const lc = libraryCourses.value.find((c) => c.id === libraryCourseId) form.value.name = lc?.name || '' - form.value.mode = lc?.mode === 'online' ? 'online' : 'offline' form.value.type = lc?.type === 'elective' ? 'elective' : 'required' form.value.hours = lc?.hours || form.value.hours form.value.lecturer_id = lc?.lecturer_id || '' @@ -1294,12 +1310,11 @@ const openDetail = async (row: TrainingCourse) => { } } -// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定, -// 适用部门变化经 watcher 自动同步参加人员名单 +// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定(形式除外, +// 000162 计划形式独立可改),适用部门变化经 watcher 自动同步参加人员名单 const onDetailLibraryCourseChange = (libraryCourseId: unknown) => { const lc = libraryCourses.value.find((c) => c.id === libraryCourseId) editForm.value.name = lc?.name || '' - editForm.value.mode = lc?.mode === 'online' ? 'online' : 'offline' editForm.value.type = lc?.type === 'elective' ? 'elective' : 'required' editForm.value.hours = lc?.hours || editForm.value.hours editForm.value.lecturer_id = lc?.lecturer_id || '' diff --git a/frontend/src/views/training/components/LibraryPanel.vue b/frontend/src/views/training/components/LibraryPanel.vue index a391547..af1374e 100644 --- a/frontend/src/views/training/components/LibraryPanel.vue +++ b/frontend/src/views/training/components/LibraryPanel.vue @@ -78,9 +78,14 @@ - + @@ -99,6 +104,7 @@ @@ -191,50 +196,8 @@ - -
- -
- - 上传课件文件 - 从知识库选择 - - - - 未选择课件(可选;上传文档自动同步知识库,也可从知识库选择已有课件) -
- -
- - - - 确定 - 收起 -
-
- 数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;保存后与上传课件同口径(下载/月培训计划带出/AI 出题共用)。 -
-
-
-
分类选项由配置中心「课程分类」维护,支持手动输入保存;讲师可为员工名册内人员或外部讲师;月培训计划「课程名称」将从本页课程中选择并自动带出此处维护的信息(不可修改);试题经列表「试题」入口维护。
+
分类选项由配置中心「课程分类」维护,支持手动输入保存;讲师可为员工名册内人员或外部讲师;月培训计划「课程名称」将从本页课程中选择并自动带出此处维护的信息(不可修改);课件上传/预览/下载经列表「课件」入口、试题经列表「试题」入口维护;发布课程前必须已上传课件。
+ + +
+ + 上传课件 + 从知识库选择 + + + +
+
+ 数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;课件变更后课程回「待核验」,重新核验后方可发布;文档类课件上传后自动同步知识库(月培训计划带出/AI 出题/对话问答共用);发布课程前必须已上传课件。 +
+ + + + + + +
+ { // ---- 新增/编辑 ---- const formVisible = ref(false) -// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析 +// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析。 +// material_name 为隐藏保留字段:课件维护移至「课件」抽屉后,编辑保存仍原值回传, +// 防止全量更新把名称登记误清(000162)。 const form = ref({ id: '', code: '', @@ -675,43 +697,19 @@ const form = ref({ suitable_members: '', category: '', type: 'required' as 'required' | 'elective', - mode: 'offline' as 'offline' | 'online', + // 新增默认「线上」(000162):线上课为常规形态;编辑随原值 + mode: 'online' as 'offline' | 'online', lecturer: '', hours: 0, material_name: '', - file_name: '', - clear_file: false, }) -// 待上传课件文件(保存成功后随行上传) -const materialInputRef = ref(null) -const pendingMaterialFile = ref(null) -const onMaterialFileChange = (e: Event) => { - const input = e.target as HTMLInputElement - pendingMaterialFile.value = input.files?.[0] || null - input.value = '' - // 上传文件与知识库课件二选一:选择文件即清掉已选知识库文档 - clearPendingKbDoc() -} -const clearPendingMaterialFile = () => { - pendingMaterialFile.value = null - if (materialInputRef.value) materialInputRef.value.value = '' -} - -// ---- 从知识库选择课件(企业培训(课件)) ---- -const kbSelectVisible = ref(false) -const pendingKbDocId = ref('') -const pendingKbDoc = ref<{ id: string; name: string } | null>(null) +// ---- 「企业培训(课件)」知识库文档(课件抽屉「从知识库选择」数据源) ---- const kbDocs = ref<{ id: string; file_name: string }[]>([]) const kbDocsLoading = ref(false) const coursewareKbRef = ref<{ id: string; name: string } | null>(null) let kbDocsLoaded = false -const toggleKbDocSelect = async () => { - kbSelectVisible.value = !kbSelectVisible.value - if (kbSelectVisible.value) await loadCoursewareKbDocs() -} - // 拉取「企业培训(课件)」知识库文档列表(惰性加载一次) const loadCoursewareKbDocs = async () => { if (kbDocsLoaded) return @@ -739,24 +737,6 @@ const loadCoursewareKbDocs = async () => { } } -const confirmKbDoc = () => { - const doc = kbDocs.value.find((d) => d.id === pendingKbDocId.value) - if (!doc) { - MessagePlugin.warning('请先选择知识库课件文档') - return - } - pendingKbDoc.value = { id: doc.id, name: doc.file_name } - // 与上传文件互斥:选定知识库文档即清掉待上传文件与已有文件移除标记 - clearPendingMaterialFile() - form.value.clear_file = false - kbSelectVisible.value = false -} - -const clearPendingKbDoc = () => { - pendingKbDoc.value = null - pendingKbDocId.value = '' -} - // 讲师下拉选项:全体员工(id=平台用户 id,与课程/需求讲师字段口径一致); // 编辑外部讲师(非 id 值)时追加临时选项避免回显裸文本丢失 const lecturerSelectOptions = computed(() => { @@ -771,9 +751,6 @@ const lecturerSelectOptions = computed(() => { }) const openForm = (row?: TrainingLibraryCourse) => { - clearPendingMaterialFile() - clearPendingKbDoc() - kbSelectVisible.value = false form.value = { id: row?.id || '', code: row?.code || '', @@ -785,12 +762,11 @@ const openForm = (row?: TrainingLibraryCourse) => { suitable_members: row?.suitable_members || (row ? '' : myDeptName.value), category: row?.category || '', type: row?.type === 'elective' ? 'elective' : 'required', - mode: row?.mode === 'online' ? 'online' : 'offline', + // 新增默认「线上」(000162);编辑随原值 + mode: row ? (row.mode === 'online' ? 'online' : 'offline') : 'online', lecturer: row?.lecturer_id || row?.lecturer_external || '', hours: row?.hours || 0, material_name: row?.material_name || '', - file_name: row?.file_name || '', - clear_file: false, } // 适合人员多选回显(000159):落库串「、」join → 数组;新增默认本部门 suitableList.value = splitSuitable(form.value.suitable_members) @@ -827,21 +803,10 @@ const onSave = async () => { lecturer_id: lecturer.lecturer_id || undefined, lecturer_external: lecturer.lecturer_external || undefined, hours: form.value.hours, + // 隐藏保留字段:课件维护已移至「课件」抽屉,编辑保存原值回传防误清(000162) material_name: form.value.material_name.trim(), - clear_file: form.value.clear_file || undefined, }) const saved = unwrap(res) - // 待上传课件文件:条目已落库后随行上传(名称登记为空时后端以文件名兜底; - // 文档类自动同步知识库「企业培训(课件)」,支持 AI 对话与出题) - if (pendingMaterialFile.value && saved?.id) { - const fd = new FormData() - fd.append('file', pendingMaterialFile.value) - await uploadCourseLibraryMaterial(saved.id, fd) - } - // 从知识库选择的课件:保存后挂接知识库文档(与上传同步同口径) - if (pendingKbDoc.value && saved?.id) { - await attachCourseLibraryMaterialFromKb(saved.id, { knowledge_id: pendingKbDoc.value.id }) - } MessagePlugin.success( form.value.id ? saved?.code @@ -852,8 +817,6 @@ const onSave = async () => { : '课程已创建,可在「月培训计划」中引用', ) formVisible.value = false - clearPendingMaterialFile() - clearPendingKbDoc() loadAll() } catch (e: any) { MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试')) @@ -946,6 +909,11 @@ const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published MessagePlugin.warning('该课程尚未核验,请先由本部门课长/经理核验确认后再发布') return } + // 发布前置校验(000162):必须有课件(名称登记不算,后端兜底同样拦截) + if (status === 'published' && !hasMaterial(row)) { + MessagePlugin.warning('该课程尚未上传课件,请先在「课件」入口上传课件文件(或从知识库选择)后再发布') + return + } try { const updated = unwrap( status === 'published' ? await publishCourseLibraryItem(row.id) : await offlineCourseLibraryItem(row.id), @@ -964,7 +932,11 @@ const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published } } -const onDownloadMaterial = async (row: TrainingLibraryCourse) => { +// 课件有无口径:已上传原始文件或已挂接知识库课件文档(名称登记不算,与发布校验同口径) +const hasMaterial = (row: TrainingLibraryCourse) => Boolean(row.file_name || row.knowledge_id) + +const onDownloadMaterial = async (row: TrainingLibraryCourse | null) => { + if (!row) return try { // getDown 直接返回 Blob(trainingTemplates 同款消费方式) const blob = await downloadCourseLibraryMaterial(row.id) @@ -979,6 +951,142 @@ const onDownloadMaterial = async (row: TrainingLibraryCourse) => { } } +// --------------------------------------------------------------------------- +// 课件管理抽屉(000162):上传/知识库选择/预览/下载/移除,交互与试题抽屉同风格 +// --------------------------------------------------------------------------- + +const materialVisible = ref(false) +const materialCourse = ref(null) +const materialUploading = ref(false) +type MaterialSourceMode = 'upload' | 'kb' +const materialSourceMode = ref('upload') +const materialFileInputRef = ref(null) +const materialFile = ref(null) +const materialKbDocId = ref('') + +const materialColumns = [ + { colKey: 'name', title: '课件名称', minWidth: 220 }, + { colKey: 'size', title: '大小', width: 110 }, + { colKey: 'source', title: '来源', width: 130 }, + { colKey: 'op', title: '操作', width: 190 }, +] + +const fmtSize = (size: number) => { + if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB` + if (size >= 1024) return `${Math.round(size / 1024)} KB` + return `${size} B` +} + +// 抽屉内课件信息行:与列表「有」口径一致(文件或知识库文档任一存在) +const materialRows = computed(() => { + const c = materialCourse.value + if (!c || !hasMaterial(c)) return [] + return [ + { + key: 'material', + name: c.file_name || c.material_name || '知识库课件文档', + size: c.file_size || 0, + source: c.file_name ? '本地上传文件' : '知识库文档', + }, + ] +}) + +// 列表行原位替换:课件变更回「待核验」等状态随接口响应同步到列表与抽屉 +const replaceLibraryRow = (updated?: TrainingLibraryCourse | null) => { + if (!updated) return + const idx = items.value.findIndex((it) => it.id === updated.id) + if (idx >= 0) items.value.splice(idx, 1, updated) + if (materialCourse.value?.id === updated.id) materialCourse.value = updated + if (questionsCourse.value?.id === updated.id) questionsCourse.value = updated +} + +const openMaterialDrawer = (row: TrainingLibraryCourse) => { + materialCourse.value = row + materialVisible.value = true + materialSourceMode.value = 'upload' + materialFile.value = null + materialKbDocId.value = '' + if (materialFileInputRef.value) materialFileInputRef.value.value = '' +} + +const onMaterialModeChange = (mode: unknown) => { + materialSourceMode.value = mode as MaterialSourceMode + if (materialSourceMode.value === 'kb') void loadCoursewareKbDocs() +} + +const onMaterialPicked = (e: Event) => { + const input = e.target as HTMLInputElement + materialFile.value = input.files?.[0] || null +} + +const onUploadMaterial = async () => { + const course = materialCourse.value + const file = materialFile.value + if (!course || !file) return + materialUploading.value = true + try { + const fd = new FormData() + fd.append('file', file) + // 名称登记为空时后端以文件名兜底;文档类自动同步知识库「企业培训(课件)」 + const updated = unwrap(await uploadCourseLibraryMaterial(course.id, fd)) + replaceLibraryRow(updated) + materialFile.value = null + if (materialFileInputRef.value) materialFileInputRef.value.value = '' + MessagePlugin.success(`课件「${updated?.file_name || file.name}」已上传;课程回「待核验」,核验后方可发布`) + } catch (e: any) { + MessagePlugin.error(apiErrorMessage(e, '课件上传失败')) + } finally { + materialUploading.value = false + } +} + +const onAttachMaterialKb = async () => { + const course = materialCourse.value + const doc = kbDocs.value.find((d) => d.id === materialKbDocId.value) + if (!course || !doc) return + materialUploading.value = true + try { + const updated = unwrap( + await attachCourseLibraryMaterialFromKb(course.id, { knowledge_id: doc.id }), + ) + replaceLibraryRow(updated) + materialKbDocId.value = '' + MessagePlugin.success(`课件「${updated?.file_name || doc.file_name}」已挂接;课程回「待核验」,核验后方可发布`) + } catch (e: any) { + MessagePlugin.error(apiErrorMessage(e, '课件挂接失败')) + } finally { + materialUploading.value = false + } +} + +// 预览:取回 Blob 后新开页签展示(文件端点对安全类型 inline,浏览器按类型渲染; +// 不可预览类型浏览器按附件处理,回退下载) +const onPreviewMaterial = async () => { + const course = materialCourse.value + if (!course) return + try { + const blob = await downloadCourseLibraryMaterial(course.id) + const url = URL.createObjectURL(blob) + window.open(url, '_blank') + // 延迟回收对象 URL,留足新页签加载时间 + setTimeout(() => URL.revokeObjectURL(url), 60_000) + } catch (e: any) { + MessagePlugin.error(apiErrorMessage(e, '课件预览失败')) + } +} + +const onRemoveMaterial = async () => { + const course = materialCourse.value + if (!course) return + try { + const updated = unwrap(await removeCourseLibraryMaterial(course.id)) + replaceLibraryRow(updated) + MessagePlugin.success('课件已移除;课程回「待核验」,需重新上传课件后方可发布') + } catch (e: any) { + MessagePlugin.error(apiErrorMessage(e, '课件移除失败')) + } +} + // ---- 导出(当前筛选结果,列口径与模板一致) ---- const onExport = async () => { @@ -1196,6 +1304,10 @@ const loadBanks = async () => { try { const res = await listLibraryCourseQuestionBanks(course.id) banks.value = unwrap(res) || [] + // 题库增删后同步列表「试题」有/无计数(该端点即本课程全部题库) + course.question_bank_count = banks.value.length + const idx = items.value.findIndex((it) => it.id === course.id) + if (idx >= 0) items.value[idx].question_bank_count = banks.value.length } catch (e: any) { MessagePlugin.error(apiErrorMessage(e, '题库加载失败')) } finally { @@ -1380,7 +1492,7 @@ const onGenerateQuestions = async () => { const course = questionsCourse.value if (!course) return if (!course.knowledge_id) { - MessagePlugin.warning('该课程课件未同步知识库,请先在课程表单中上传课件文档后再 AI 出题') + MessagePlugin.warning('该课程课件未同步知识库,请先在「课件」入口上传课件文档后再 AI 出题') return } genLoading.value = true @@ -1583,39 +1695,9 @@ onMounted(loadAll) font-size: var(--app-text-sm); } -// 课件字段:名称登记 + 文件上传行 -.material-field { - width: 100%; -} - -.material-upload-row { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 8px; - margin-top: 8px; -} - -.material-upload-input { - display: none; -} - -.material-file-name { - max-width: 220px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - color: var(--td-text-color-secondary); - font-size: var(--app-text-sm); -} - -.material-placeholder { - color: var(--td-text-color-placeholder); - font-size: var(--app-text-sm); -} - -.material-file-tag { - margin-left: 6px; +// 列表「有」标签可点击直达维护抽屉 +.cell-link { + cursor: pointer; } // 批量导入弹窗:模板下载 + Excel 上传一行排布(与培训计划导入同款) diff --git a/internal/application/repository/training_library.go b/internal/application/repository/training_library.go index 9b6d2e8..3df655b 100644 --- a/internal/application/repository/training_library.go +++ b/internal/application/repository/training_library.go @@ -63,8 +63,10 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin var items []*types.TrainingCourseLibrary // lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列); // owner_dept_name 联查部门名(所属部门存 org_depts id); - // creator_name 联查创建人姓名(display_name 优先,回退 username 工号)。 - err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name"). + // creator_name 联查创建人姓名(display_name 优先,回退 username 工号); + // question_bank_count 关联题库数(相关子查询,软删不计;列表「试题」有/无)。 + err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name, "+ + "(SELECT COUNT(*) FROM tr_question_banks qb WHERE qb.library_course_id = tr_course_library.id AND qb.tenant_id = tr_course_library.tenant_id AND qb.deleted_at IS NULL) AS question_bank_count"). Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id"). Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL"). Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id"). diff --git a/internal/application/service/training_course.go b/internal/application/service/training_course.go index 7e960c6..ab82a52 100644 --- a/internal/application/service/training_course.go +++ b/internal/application/service/training_course.go @@ -130,10 +130,12 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str } // applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153): -// 课程名称/类型/形式随课程管理主数据锁定;讲师 000161 起计划侧可改(更新路径 -// 不再覆盖,改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时 -// 讲师/学时/课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按 -// 原值保存(fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。 +// 课程名称/类型随课程管理主数据锁定;形式(mode)为计划侧独立字段——计划形式 +// 指本次培训线上办还是线下办,与课程主数据的线上课/线下课口径不同,不随课程 +// 带出,由创建/调整表单自行选择;讲师 000161 起计划侧可改(更新路径不再覆盖, +// 改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时讲师/学时/ +// 课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存 +// (fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。 func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary { if course.LibraryCourseID == "" { return nil @@ -143,10 +145,9 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI logger.Error(ctx, "Failed to load library course for plan binding", err, "library_course_id", course.LibraryCourseID) return nil } - // 锁定字段:随课程管理主数据,请求侧取值一律覆盖。 + // 锁定字段:随课程管理主数据,请求侧取值一律覆盖(形式除外,见上)。 course.Name = item.Name course.Type = item.Type - course.Mode = item.Mode if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") { // 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。 course.LecturerID = item.LecturerID diff --git a/internal/application/service/training_library.go b/internal/application/service/training_library.go index 00e7024..085ed29 100644 --- a/internal/application/service/training_library.go +++ b/internal/application/service/training_library.go @@ -179,7 +179,8 @@ func (s *trainingService) GetCourseLibraryItem(ctx context.Context, tenantID uin // SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 / // offline 已下线;培训中心「和信课程」目录仅展示已发布课程。 -// 发布前置校验核验状态(000157):仅「已确认」课程可发布。 +// 发布前置校验核验状态(000157):仅「已确认」课程可发布; +// 发布必须有课件(名称登记不算,须已上传课件文件或已挂接知识库课件文档)。 func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error { if status != "published" && status != "offline" { return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)") @@ -191,6 +192,9 @@ func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, ten if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed { return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name)) } + if status == "published" && strings.TrimSpace(item.FileKey) == "" && strings.TrimSpace(item.KnowledgeID) == "" { + return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name)) + } return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status) } @@ -434,6 +438,29 @@ func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tena return rc, item.FileName, nil } +// RemoveCourseLibraryMaterial 移除课程课件原始文件/知识库挂接(名称登记保留, +// 上传课件时仍会以文件名兜底名称登记):文件与知识库文档字段清空,课件内容 +// 变更即回待核验(000157 同口径),移除后课程不满足发布课件前置。 +func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) { + item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id) + if err != nil || item == nil { + return nil, werrors.NewNotFoundError("课程不存在") + } + if item.FileKey == "" && item.KnowledgeID == "" { + return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除") + } + item.FileKey, item.FileName, item.FileSize = "", "", 0 + item.KnowledgeID = "" + item.VerifyStatus = types.CourseLibraryVerifyPending + item.ConfirmedBy = "" + item.ConfirmedAt = nil + if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil { + return nil, err + } + logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s operator=%s", tenantID, id, updaterID) + return item, nil +} + // AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有 // 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。 // 原始文件字段清空,名称登记为空时以文档名兜底。 diff --git a/internal/application/service/training_library_publish_test.go b/internal/application/service/training_library_publish_test.go new file mode 100644 index 0000000..2751275 --- /dev/null +++ b/internal/application/service/training_library_publish_test.go @@ -0,0 +1,181 @@ +package service + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "academy/internal/application/repository" + "academy/internal/types" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// newCourseLibraryFixture 构建 sqlite + 真实仓储的 trainingService,专测课程 +// 管理发布课件前置(发布必须有课件)、计划形式与课程形式解耦、列表题库计数。 +// GetCourseLibraryItem/ListCourseLibrary LEFT JOIN users/org_depts 取姓名列, +// sqlite 下以最小列表兜底(仅被 JOIN 读取,不落数据)。 +func newCourseLibraryFixture(t *testing.T) (*trainingService, *gorm.DB, uint64) { + t.Helper() + db, err := gorm.Open( + sqlite.Open(filepath.Join(t.TempDir(), "training_library.db")+"?_busy_timeout=5000&_journal_mode=WAL"), + &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}, + ) + require.NoError(t, err) + raw, err := db.DB() + require.NoError(t, err) + t.Cleanup(func() { _ = raw.Close() }) + require.NoError(t, db.AutoMigrate(&types.TrainingCourseLibrary{}, &types.TrainingQuestionBank{})) + for _, ddl := range []string{ + "CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT DEFAULT '', display_name TEXT DEFAULT '')", + "CREATE TABLE org_depts (id TEXT PRIMARY KEY, tenant_id INTEGER DEFAULT 0, name TEXT DEFAULT '', deleted_at DATETIME NULL)", + } { + require.NoError(t, db.Exec(ddl).Error) + } + const tenantID = uint64(42) + svc := &trainingService{repo: repository.NewTrainingRepository(db), db: db} + return svc, db, tenantID +} + +// seedCourseLibraryItem 直接落一条课程管理条目(绕过编号生成等依赖)。 +func seedCourseLibraryItem(t *testing.T, db *gorm.DB, tenantID uint64, item *types.TrainingCourseLibrary) { + t.Helper() + if item.TenantID == 0 { + item.TenantID = tenantID + } + require.NoError(t, db.Create(item).Error) +} + +// 发布必须有课件(000162 口径):名称登记不算,须有原始文件或知识库课件文档; +// 下线不要求课件;未核验仍先行拦截(校验顺序:核验在前课件在后)。 +func TestSetCourseLibraryPublishStatusRequiresCourseware(t *testing.T) { + svc, db, tenantID := newCourseLibraryFixture(t) + ctx := context.Background() + + nameOnly := &types.TrainingCourseLibrary{ID: "cl-name-only", Name: "仅名称登记课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, MaterialName: "安全操作规范", Mode: types.TrainingCourseModeOnline} + withFile := &types.TrainingCourseLibrary{ID: "cl-with-file", Name: "已传文件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, FileKey: "fk-1", FileName: "a.pptx", Mode: types.TrainingCourseModeOnline} + withKb := &types.TrainingCourseLibrary{ID: "cl-with-kb", Name: "知识库课件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, KnowledgeID: "kb-1", FileName: "b.docx", Mode: types.TrainingCourseModeOnline} + pending := &types.TrainingCourseLibrary{ID: "cl-pending", Name: "待核验课程", VerifyStatus: types.CourseLibraryVerifyPending, FileKey: "fk-2", FileName: "c.pptx", Mode: types.TrainingCourseModeOnline} + for _, item := range []*types.TrainingCourseLibrary{nameOnly, withFile, withKb, pending} { + seedCourseLibraryItem(t, db, tenantID, item) + } + + // 仅名称登记:拦截。 + err := svc.SetCourseLibraryPublishStatus(ctx, tenantID, nameOnly.ID, "published") + require.Error(t, err) + require.True(t, strings.Contains(err.Error(), "课件"), "应提示缺少课件,实际: %s", err.Error()) + + // 已上传原始文件:放行。 + require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, withFile.ID, "published")) + // 仅挂接知识库文档:放行。 + require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, withKb.ID, "published")) + + // 未核验(待核验)先行拦截,课件校验在其后。 + err = svc.SetCourseLibraryPublishStatus(ctx, tenantID, pending.ID, "published") + require.Error(t, err) + require.True(t, strings.Contains(err.Error(), "核验"), "应提示未核验,实际: %s", err.Error()) + + // 下线不要求课件:名称登记课程可直接下线。 + require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, nameOnly.ID, "offline")) +} + +// 移除课件:文件/知识库字段清空、名称登记保留、回待核验并清核验痕迹; +// 无课件条目移除直接拒绝。 +func TestRemoveCourseLibraryMaterial(t *testing.T) { + svc, db, tenantID := newCourseLibraryFixture(t) + ctx := context.Background() + confirmedAt := timeNowPtr() + item := &types.TrainingCourseLibrary{ + ID: "cl-remove", Name: "待移除课件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, + ConfirmedBy: "u-verifier", ConfirmedAt: confirmedAt, + FileKey: "fk-3", FileName: "d.pptx", FileSize: 1024, KnowledgeID: "kb-2", + MaterialName: "登记名称保留", Mode: types.TrainingCourseModeOnline, + } + seedCourseLibraryItem(t, db, tenantID, item) + + updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op") + require.NoError(t, err) + require.Empty(t, updated.FileKey) + require.Empty(t, updated.FileName) + require.Zero(t, updated.FileSize) + require.Empty(t, updated.KnowledgeID) + require.Equal(t, "登记名称保留", updated.MaterialName) + require.Equal(t, types.CourseLibraryVerifyPending, updated.VerifyStatus) + require.Empty(t, updated.ConfirmedBy) + require.Nil(t, updated.ConfirmedAt) + + // 落库复核(更新为全列覆盖,防只改内存对象)。 + stored, err := svc.GetCourseLibraryItem(ctx, tenantID, item.ID) + require.NoError(t, err) + require.Empty(t, stored.FileKey) + require.Empty(t, stored.KnowledgeID) + require.Equal(t, types.CourseLibraryVerifyPending, stored.VerifyStatus) + + // 已无课件再移除:拒绝。 + _, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op") + require.Error(t, err) +} + +func timeNowPtr() *time.Time { + v := time.Now() + return &v +} + +// 计划「形式」与课程「线上/线下」独立(000162):绑定带出名称/类型,不覆盖 +// 计划侧 mode——课程线下 + 计划线上、课程线上 + 计划线下双向保持请求值。 +func TestApplyLibraryCourseBindingKeepsPlanMode(t *testing.T) { + svc, db, tenantID := newCourseLibraryFixture(t) + ctx := context.Background() + seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "lib-offline", Name: "线下课程A", Type: "required", Mode: types.TrainingCourseModeOffline}) + seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "lib-online", Name: "线上课程B", Type: "elective", Mode: types.TrainingCourseModeOnline}) + + // 线下课程 + 线上计划:计划形式保持线上。 + plan := &types.TrainingCourse{ID: "plan-1", LibraryCourseID: "lib-offline", Name: "占位", Mode: types.TrainingCourseModeOnline, Type: "elective"} + hit := svc.applyLibraryCourseBinding(ctx, tenantID, plan, true) + require.NotNil(t, hit) + require.Equal(t, types.TrainingCourseModeOnline, plan.Mode) + require.Equal(t, "线下课程A", plan.Name) + require.Equal(t, "required", plan.Type) + + // 线上课程 + 线下计划:计划形式保持线下。 + plan2 := &types.TrainingCourse{ID: "plan-2", LibraryCourseID: "lib-online", Name: "占位", Mode: types.TrainingCourseModeOffline, Type: "required"} + hit2 := svc.applyLibraryCourseBinding(ctx, tenantID, plan2, false) + require.NotNil(t, hit2) + require.Equal(t, types.TrainingCourseModeOffline, plan2.Mode) + require.Equal(t, "线上课程B", plan2.Name) + require.Equal(t, "elective", plan2.Type) +} + +// 列表题库计数:仅统计未软删的关联题库,question_bank_count 随列表返回。 +func TestListCourseLibraryQuestionBankCount(t *testing.T) { + svc, db, tenantID := newCourseLibraryFixture(t) + ctx := context.Background() + seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "cl-banks", Name: "有两库课程", Mode: types.TrainingCourseModeOnline}) + seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "cl-deleted", Name: "仅软删库课程", Mode: types.TrainingCourseModeOnline}) + deletedAt := timeNowPtr() + banks := []*types.TrainingQuestionBank{ + {ID: "qb-1", TenantID: tenantID, LibraryCourseID: "cl-banks", Name: "题库1"}, + {ID: "qb-2", TenantID: tenantID, LibraryCourseID: "cl-banks", Name: "题库2"}, + {ID: "qb-3", TenantID: tenantID, LibraryCourseID: "cl-deleted", Name: "软删题库", DeletedAt: deletedAt}, + // 其他课程的题库不应计入。 + {ID: "qb-4", TenantID: tenantID, LibraryCourseID: "cl-other", Name: "别家题库"}, + } + for _, b := range banks { + require.NoError(t, db.Create(b).Error) + } + + items, total, err := svc.ListCourseLibraryItems(ctx, tenantID, nil) + require.NoError(t, err) + require.EqualValues(t, 2, total) + counts := map[string]int{} + for _, it := range items { + counts[it.ID] = it.QuestionBankCount + } + require.Equal(t, 2, counts["cl-banks"], fmt.Sprintf("计数结果: %v", counts)) + require.Equal(t, 0, counts["cl-deleted"], "软删题库不应计入") +} diff --git a/internal/handler/training/training_library.go b/internal/handler/training/training_library.go index c039666..68b5037 100644 --- a/internal/handler/training/training_library.go +++ b/internal/handler/training/training_library.go @@ -334,6 +334,20 @@ func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": true, "data": item}) } +// RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove +// — 移除课程课件原始文件/知识库挂接(名称登记保留,课件变更即回待核验)。 +func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) { + if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) { + return + } + item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c)) + if err != nil { + _ = c.Error(err) + return + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": item}) +} + // CourseLibraryMaterialFile GET /training/course-library/:id/material/file — // 课件原始文件流(下载/在线预览)。 func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) { diff --git a/internal/router/routes_training.go b/internal/router/routes_training.go index 30a2947..6a59a72 100644 --- a/internal/router/routes_training.go +++ b/internal/router/routes_training.go @@ -105,6 +105,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial) // material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。 trainingGroup.POST("/course-library/:id/material/from-kb", g.Contributor(), h.AttachCourseLibraryMaterialFromKb) + // material/remove 移除课件(名称登记保留,课件变更即回待核验)。 + trainingGroup.POST("/course-library/:id/material/remove", g.Contributor(), h.RemoveCourseLibraryMaterial) trainingGroup.GET("/course-library/:id/material/file", h.CourseLibraryMaterialFile) // ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ---- trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks) diff --git a/internal/types/interfaces/training.go b/internal/types/interfaces/training.go index 02eb8bb..9263618 100644 --- a/internal/types/interfaces/training.go +++ b/internal/types/interfaces/training.go @@ -346,6 +346,8 @@ type TrainingService interface { // AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择 // 已有文档作为课程课件(与上传同步同口径)。 AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) + // RemoveCourseLibraryMaterial 移除课程课件(文件/知识库挂接清空,名称登记保留)。 + RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) diff --git a/internal/types/training.go b/internal/types/training.go index 9a9d8cf..a9a6f9a 100644 --- a/internal/types/training.go +++ b/internal/types/training.go @@ -637,6 +637,8 @@ type TrainingCourseLibrary struct { LecturerName string `json:"lecturer_name" gorm:"->"` // CreatorName 创建人姓名(联查 users 只读,不落库;列表「创建人」列展示)。 CreatorName string `json:"creator_name" gorm:"->"` + // QuestionBankCount 关联题库数(联查只读,不落库;列表「试题」有/无展示)。 + QuestionBankCount int `json:"question_bank_count" gorm:"->"` // OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。 OwnerDeptName string `json:"owner_dept_name" gorm:"->"` CreatedAt time.Time `json:"created_at"`