25 Commits
Author SHA1 Message Date
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
runny f43fbef5db feat(企微签到):逻辑:员工使用企微扫码后直接跳出签到页面,在签到页面对该课程进行点击签到!
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码);
补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
2026-11-25 11:02:48 +08:00
runny 9950a28346 feat(培训课程相关调整):1.培训计划中的形式”线上/线下“与课程中的”线上/线下“独立字段!,培训计划中是指线上培训还是线下培训,课程中是指该课程是线上课还是线下课,两者不能共用相互独立!
deploy-hxtesting / build-and-deploy (push) Successful in 1m18s
2.创建课程时课程默认是”线上“,发布课程时必须要有课件!
3.课程管理中的课件上传预览下载交互样式,按维护”试题“交互样式风格来!列表中增加一列”试题“,列表中”试题“、”课件“按实际情况只展示”有/无“即可!
2026-11-25 10:23:10 +08:00
runny ea0524c445 feat(优化):1.人事课孙凯发布月培训选我刘义亮参加培训如图一所示,但我的培训中却线上”我主讲“?请核实!
deploy-hxtesting / build-and-deploy (push) Successful in 1m8s
2.培训中心增加2个统计”我主讲X门“、”我参加X门“如图二所示
3.如图三培训详情页面右上角增加一个【培训签到】按钮,点击自动跳转到如图四”培训签到“页面自动打开该课程签到详情,
4.如图四所示增加一个【培训详情】块,点击自动返回如图三该培训详情页面!
请在本地修改代码!
2026-11-25 08:47:05 +08:00
runny 11450bdb96 fix(我的培训):「我的培训」的“与我相关”判定(学习任务/讲师/部门范围)不含「参加人员」——线下课不生成学习任务,参加人员只落场次名单与文案,刘义亮(资讯组)被课程部门范围(人事课)拦在页签外。
deploy-hxtesting / build-and-deploy (push) Successful in 20m39s
2026-11-24 21:22:27 +08:00
runny 448fbcdaff feat(org): 组织架构新增「收编到本空间」,批量修正成员登录默认落点
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
员工首登自动开通个人空间(create_personal 默认)后,归属空间(users.tenant_id)
与「最近活跃租户」偏好停在个人空间,登录后看到的是个人空间里那份空的组织
架构/培训数据,模板下载也没有部门下拉。空间 Owner 现可一键收编:
1. GET /org/employees/adoptable 收编预览:归属空间不在本空间的活跃成员
   (COALESCE 兜底 NULL 归属,联查名册标记与归属空间名供确认);
2. POST /org/employees/adopt-home 批量收编:逐条校验不整批失败,非本空间
   成员/停用/跨空间账号/已归属本空间逐条跳过并回传原因;归属指针与最近
   活跃租户偏好一起改指本空间(登录路径优先读偏好,只改归属会被旧偏好
   拉回),成员关系/角色/个人空间数据不动,可经空间切换器改回,非破坏性;
3. 收编成功者补跑自动入册(EnsureEmployeesForUsers 仅补空幂等),
   同步部门自动匹配进名册;
4. 单条 rbac.member_home_adopted 审计(best-effort);路由 g.Owner() 限定,
   与成员批量导入/Casdoor 同步同权限级别;
5. 收编依赖只引 repository 层(UserRepository/TenantMemberRepository),
   避开 tenantMemberService→OrgCenterService→userService→memberService
   的 DI 环;
6. 前端组织架构页新增「收编到本空间」入口(仅 hasRole('owner') 可见)+
   预览确认弹窗(与 OA 同步弹窗同两段式交互);顺手补齐
   OrgEmployee.wecom_userid 缺失的存量类型缺口(type-check 阻断项)。
测试:服务层新增收编落点+偏好/六类跳过/守卫 3 例;仓库层 sqlite 用例覆盖
NULL 归属兜底与停用/已归属排除;既有 org/member/casdoor/培训模板用例无回归。
2026-11-24 18:16:51 +08:00
runny 8f225ecea9 feat(feat):
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
1.将职称角色中的“从OA同步企微账号”及设置角色、“员工与部门在「组织架构」中统一维护,此处仅配置职称角色”迁移到组织架构页面中,
2.平台新增成员自动添加到“组织架构”页面自动匹配对应部门;
3.在“组织架构”页面可直接设置角色
4.“组织架构”页面职称按名称、工号、部门查找员工
5.新增成员默认放在最上面按时间倒序排列
6.所有登录平台的用户直接默认打开AI对话页面
7.页面3、4中的”AIDO“改为”和信智汇学院“
2026-11-24 14:38:20 +08:00
runny 196478114c fix(onboarding): 租户序列避让保留 ID 并为存量空间补齐开箱默认库
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
根因(26040006 等首用户空间零知识库):
- 000000 初始迁移把 tenants_id_seq 起点设为 10000,恰好等于内置模型宿主
  保留租户 id(DefaultBuiltinModelTenantID=10000):全新环境的第一个用户
  空间必然撞上 SeedTenantDefaults 的「永不 seed」豁免,一个默认库都没有;
  后续空间(10001+)正常。内置模型行(tenant_id=10000)被真实空间占住,
  还存在归属歧义隐患
- 注册引导是创建时一次性动作,存量空间因引导当时失败(如模型未就绪)或
  上述碰撞而缺库时,此后永不补建

修复:
- migration 000160:租户序列推到 10001 之后——全新库从 10001 起号(10000
  永久保留给内置模型宿主),存量库按 max(id) 连续续号不受影响
- SeedTenantDefaults 拆出 seedStarterKB 供创建时引导与自愈共用;保留租户
  豁免注释同步更新
- 新增 EnsureTenantDefaultKnowledgeBases 惰性自愈:挂在知识库列表读路径
  (幂等/fail-open/进程内互斥防并发重复建档)——企业培训课件/题库两库恒补
  (Source 去重),「新手入门」仅零库空间补建(不复活用户主动删除的入门库)

效果:26040006(租户 10000)等存量用户打开「知识库」页即自动补齐 3 个默认
库;全新环境的首个用户空间不再撞保留 id
2026-11-24 11:10:14 +08:00
runny 42042ca8bd build(docker): 缺失 docker/prebuilt 的构建机兜底为全量构建路径
deploy-hxtesting / build-and-deploy (push) Successful in 1m53s
2026-11-24 10:32:35 +08:00
runny 7e1e670f0a build(ci): hxtesting 同步代码幂等化,部署目录残留改动自动 stash 留底
deploy-hxtesting / build-and-deploy (push) Failing after 1s
2026-11-24 10:28:10 +08:00
runny 8bd02e7c7e build(docker): 镜像构建新增离线预构建快速通道
deploy-hxtesting / build-and-deploy (push) Failing after 0s
- docker/prebuilt/ 携带宿主机交叉编译产物(Academy 二进制 + gojieba/yanyiwu
  运行时依赖)时,跳过 go mod download、license 归档、源码编译等联网步骤,
  直接装填预构建产物,适配网络受限构建环境
- 目录不入库(.gitignore 锚定 /docker/prebuilt/,与 artifacts/browserskill
  同口径):仅构建宿主机本地存在,上游在线构建走原路径不受影响
- .gitignore 另忽略本地 .cgo-sqlite/ 构建残留
2026-11-24 10:04:18 +08:00
runny 4112de0703 feat(onboarding): 注册引导确保企业培训默认库并补齐模型自动配置
空间引导(SeedTenantDefaults):
- 按 Source 标记独立幂等确保「企业培训(课件)/(题库)」两个系统默认库,
  CASDOOR/OIDC 注册、平台注册、管理员建空间统一触发;与培训域上传链路
  同源复用(不会重复建档),fail-open 不阻断注册主流程

模型自动配置(默认模型优先,否则该类型第一个 active):
- 智能体创建后端兜底补齐 ReRank 模型,与主模型同口径(无可用重排模型留空)
- 智能体/知识库编辑弹窗 applyDefaultModelsIfEmpty 改新建/编辑通用:
  仅空字段补默认、绝不覆盖用户已选;存量空模型数据打开即可直接保存,
  不再被「模型必填」卡住手动配置
2026-11-24 10:04:11 +08:00
runny 6594f97e3c feat(user): 全局身份展示改用姓名 display_name
- UserInfo 下发 display_name(/auth/me、登录等返回 UserInfo 的接口一并下发):
  工号式 IdP 的 username 是工号,界面展示姓名用
- 左下角用户菜单:多空间身份行优先姓名(未设置回落账号),单空间行显示姓名
  (未设置回落邮箱);头像占位首字优先取姓名首字
2026-11-24 10:04:04 +08:00
runny 0819f8c4d1 feat(training): 需求联动课程管理、适合人员多选、跨空间参与与计划讲师回写(000158-000161)
000158 需求单联动课程管理:
- tr_demands 新增 library_course_id:填报/导入按课程名称在课程管理精准匹配,
  命中自动关联,未命中自动新增待核验课程(000157 流转,发布前须签核完成);
  匹配/建档失败整批回滚并透出原因,不静默跳过
- 需求所属部门强制为填报人本人部门:新建按提报人档案落库(忽略请求值防绕过,
  无部门档案阻断),编辑保留原部门;批量导入按 Excel「部门」列做归属校验
- 编辑时课程名未变保留原课程关联,全量更新不误清

000159 适合人员部门多选:
- tr_course_library.suitable_members 拓宽至 VARCHAR(512):存「、」分隔多部门名
  或「全部」,存量单值/自由文本兼容(分隔符匹配时归一)
- 课程管理/需求表单改多选交互,「全部」与具体部门互斥

000160 企业培训跨空间参与:
- 培训域数据空间按员工档案归属解析(当前空间有培训档案优先,否则回落最早
  在职档案所在空间),路由组 TrainingTenantResolution 中间件统一注入
- 中间件同步回落请求上下文执行租户:课件文件流(GetKnowledgeFile)、培训
  知识库 ensure 等 ctx 租户链路落在档案空间;caller 身份保持当前工作区,
  授权口径不变(修复跨空间学员课件预览 403「Permission denied」与文件流 404)
- 课程学习详情页课件预览统一走培训域文件流(/training/materials/:id/file),
  不再请求知识库守卫路由(/knowledge/:id/preview);附空间解析中间件单元测试
- 培训中心「和信课程」目录(scope=catalog):已发布 + 适合人员覆盖即可见;
  卡片点开即学(课件在线预览抽屉 + 下载);计划无材料行时以课程管理条目
  合成课件回退取流
- /training/members/me 联查返回部门名,支撑适合人员匹配与表单默认值

000161 计划讲师回写与发布校验:
- 月培训计划讲师计划侧可改,改动回写课程管理主数据并重置待核验(发布前须
  重新签核),同步补讲师 lecturer 角色绑定
- 发布必填校验:关联课程管理且已签核、参加人员;线下计划另需授课时间/地点/
  讲师(线上计划豁免);跨场次名单去重成员数校验
2026-11-24 10:03:58 +08:00
syadmin 3c8b595064 Merge branch 'main' 2026-11-21 11:46:39 +08:00
syadmin 11ce1c3c0c docs(deploy): 双区入口更新为域名 kb/kbt 并注记证书与回调口径 2026-11-21 11:46:14 +08:00
102 changed files with 7427 additions and 1169 deletions

No files matched your search

+5 -1
View File
@@ -22,9 +22,13 @@ jobs:
set -e set -e
cd "$DEPLOY_DIR" cd "$DEPLOY_DIR"
git fetch origin git fetch origin
git checkout -q -B test origin/test # 幂等发布:部署目录若残留未提交改动/未跟踪文件(如服务器上临时调试遗留),
# 先整体 stash 留底(-u 含未跟踪文件;不碰 .gitignore 的本地配置),再强制对齐远端
git stash push -u -m "deploy-autostash $(date +%F_%T)" || true
git checkout -f -q -B test origin/test
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV" echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
echo "当前部署提交: $(git log --oneline -1)" echo "当前部署提交: $(git log --oneline -1)"
echo "同步后残留脏文件: $(git status --porcelain | wc -l) 项"
- name: 构建镜像(app + frontend,ARM64 原生) - name: 构建镜像(app + frontend,ARM64 原生)
run: | run: |
+5
View File
@@ -73,5 +73,10 @@ miniprogram/project.private.config.json
# Locally built BrowserSkill runtime and extension bundles # Locally built BrowserSkill runtime and extension bundles
/artifacts/browserskill/ /artifacts/browserskill/
# Offline Docker build fast-path artifacts (prebuilt binary + runtime deps,
# carried on the build host only — never committed, see docker/Dockerfile.app)
/docker/prebuilt/
# Local DuckDB extension extraction scratch dir (training template debugging) # Local DuckDB extension extraction scratch dir (training template debugging)
tmp-extract-duckdb/ tmp-extract-duckdb/
.cgo-sqlite/
+22 -3
View File
@@ -83,10 +83,20 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
# so that module's go.mod must exist before `go mod download`. # so that module's go.mod must exist before `go mod download`.
COPY go.mod go.sum ./ COPY go.mod go.sum ./
COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod
# 离线快速通道(网络受限环境):docker/prebuilt/ 携带宿主机交叉编译的产物时,
# 跳过 go mod download 等联网步骤,直接装填预构建二进制与 gojieba 运行时依赖。
# 目录不入库(与 artifacts/browserskill 同口径),上游构建走下方原有路径不受影响。
COPY docker/prebuilt/ /app/prebuilt/
# 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖, # 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖,
# 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载) # 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载)
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/ if [ -f /app/prebuilt/Academy ]; then \
mkdir -p /go/pkg/mod/github.com/yanyiwu && \
tar -xzf /app/prebuilt/yanyiwu.tar.gz -C /go/pkg/mod/github.com/yanyiwu && \
cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
else \
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
fi
COPY cmd/download cmd/download COPY cmd/download cmd/download
# DuckDB extensions (spatial/excel): prefer a local seed tarball exported from # DuckDB extensions (spatial/excel): prefer a local seed tarball exported from
# a previously built image (artifacts/duckdb_extensions/seed.tar) — # a previously built image (artifacts/duckdb_extensions/seed.tar) —
@@ -100,7 +110,13 @@ RUN if [ -s /tmp/duckdb-seed.tar ]; then \
go run cmd/download/duckdb/duckdb.go; \ go run cmd/download/duckdb/duckdb.go; \
fi fi
COPY . . COPY . .
RUN bash ./scripts/copy-licenses.sh /license-bundle # license 归档属发布输入(联网逐模块校验),离线快速通道下跳过,不影响运行时功能
RUN if [ -f /app/prebuilt/Academy ]; then \
echo "==> Offline fast-path: skip license bundle"; \
mkdir -p /license-bundle/licenses/sources; \
else \
bash ./scripts/copy-licenses.sh /license-bundle; \
fi
# Get version and commit info for build injection # Get version and commit info for build injection
ARG VERSION_ARG ARG VERSION_ARG
@@ -163,7 +179,10 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
objcopy --remove-section "$s" "$a" || true; \ objcopy --remove-section "$s" "$a" || true; \
done; \ done; \
done; \ done; \
if [ "$WITH_ANYDOC" = "1" ]; then \ if [ -f /app/prebuilt/Academy ]; then \
echo "==> Using prebuilt binary from docker/prebuilt/"; \
cp /app/prebuilt/Academy /app/Academy; \
elif [ "$WITH_ANYDOC" = "1" ]; then \
make build-prod GO_BUILD_TAGS=anydoc; \ make build-prod GO_BUILD_TAGS=anydoc; \
else \ else \
make build-prod; \ make build-prod; \
+5 -3
View File
@@ -43,9 +43,11 @@
| 项 | 值 | | 项 | 值 |
| --- | --- | | --- | --- |
| 生产服入口 | http://192.168.100.230:8802(域名绑定待 DNS 管理员登记后更新) | | 生产服入口 | **https://kb.well-trust.com**(ai30 nginx 443 反代 8802;备选直连 http://192.168.100.230:8802) |
| 测试服入口 | **https://kbt.well-trust.com**(同一证书/vhost 反代 hxtesting 8801;备选 http://192.168.100.192:8801) |
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy | | 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
| 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) | | 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) |
| 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 `http://192.168.100.230:8802/api/v1/auth/oidc/callback`(域名定稿后同步追加域名回调);client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) | | 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 IP 与 https://kb.well-trust.com 两路 + localhost:5173;client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) |
| Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行前快照) | | Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行)、`application_bak_20261120`(域名回调更新前) |
| 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) | | 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) |
| 域名/证书 | kb+kbt SAN 一张(`/data/ai-platform/.certbot/config/live/kb.well-trust.com/`),DNS A 记录与 TXT 验证均走阿里 API(凭据 `aliyun-welltrust.ini`)自动完成,续期 dns-aliyun 全自动;vhost=`/etc/nginx/conf.d/kb-academy.conf`(预写件 `/data/ai-platform/kb-academy-nginx.conf`,装载需一次 sudo) |
+2 -2
View File
@@ -47,8 +47,8 @@
| 项 | 值 | | 项 | 值 |
| --- | --- | | --- | --- |
| 测试服入口 | http://192.168.100.192:8801(FRONTEND_PORT=8801,登记册 88xx 平台段) | | 测试服入口 | **https://kbt.well-trust.com**(ai30 nginx 反代;备选 http://192.168.100.192:8801,FRONTEND_PORT=8801,登记册 88xx 平台段) |
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy | | 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
| 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) | | 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) |
| 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 与本地 5173) | | 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 / https://kbt.well-trust.com 与本地 5173) |
| 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) | | 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) |
@@ -0,0 +1,290 @@
# 企微扫码签到免登 · 落地方案
> 状态:**已实施(P0+P1 核心,待企微后台配置后联调)** —— 见文末「实施记录」
> 日期: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. ~~**宽限期**~~ → 已按"加宽限"实施(`rotation_grace_sec=30`,规则配置可关为 0)。
2. **企微后台三项配置**(可信域名/校验文件/可信IP)需管理员先落地,`well-trust.com` 的 ICP 备案状态需确认——这是整个方案的开关,建议最先验证。
## 10. 实施记录(2026-11-25)
### 变更文件
| 层 | 文件 | 内容 |
|---|---|---|
| 企微客户端 | `internal/im/wecom/proactive_client.go` | `BuildOAuthAuthorizeURL`(snsapi_base 授权链接)+ `GetOAuthUserID`(code 换 userid,token 过期错误码清缓存) |
| 推送适配 | `internal/im/wecompush/client.go` | `OAuthClientForTenant`(与消息推送同一套自建应用凭据) |
| 类型 | `internal/types/training.go` | `CheckinInput`/`WecomCheckinCourse`/`WecomCheckinPage`/`WecomCheckinSession` DTO;`tr_sign_codes.prev_token/prev_expire_at`、`tr_sign_records.nonce` 列 |
| 接口 | `internal/types/interfaces/training.go`、`user.go` | 仓库 3 个新方法(全局查码/企微反查/nonce 查重);服务新增免登 3 方法 + `Checkin` 签名改为 `CheckinInput`;`UserService.SessionResponseForUser`(与 /auth/login 同构的会话组装) |
| 用户服务 | `internal/application/service/user.go` | `SessionResponseForUser`:登录落点解析 + token 对 + 租户 + memberships 一次成型 |
| 免登服务 | `internal/application/service/training_wecom_oauth.go`(新) | `WecomCheckinAuthURL` / `WecomCheckinSession`(code→userid→绑定反查→签发 JWT→落地页数据)/ `WecomCheckinPage` / `resolveWecomSignCode`(前码宽限)/ `sameBeijingDay` |
| 签到域 | `internal/application/service/training_course.go` | `Checkin` 规则增强(当天性/工号+名单硬拒/nonce 防重放/时钟偏差/前码宽限);`GetSignCode` 惰性轮换;`rotateSignCode`;`CreateSignCode` 有效期改为 `min(now+rotation, 场次总有效期)` |
| 代录 | `internal/application/service/training_ops.go` | `CheckinFor` 适配新签名;代录不带工号/nonce,不受严格链路约束 |
| HTTP | `internal/handler/training/training.go` | `CheckinRequest` 增 `employee_no/nonce/client_ts`;`WecomCheckinAuth/Session/Page` 三个处理器 |
| 路由 | `internal/router/routes_training.go` | 两个匿名入口直挂 v1 + `WecomCheckinRateLimit`;`POST /training/wecom/checkin-page` 入 trainingGroup(Viewer) |
| 鉴权 | `internal/middleware/auth.go`、`auth_public_ratelimit.go` | noAuthAPI 白名单两行;**签到专用限流桶 600/min/IP**(教室共享出口 IP,复用 auth 共享桶 30/min 会整批 429) |
| 容器 | `internal/container/container.go` | `WecomOAuthBackend` provide + `trainingWecomBackend` 增 `OAuthClientForTenant` 适配 |
| 迁移 | `migrations/versioned/000162_training_sign_rotation.{up,down}.sql` | 两表三列,幂等 |
| 前端 API | `frontend/src/api/training/index.ts` | `getCheckinAuthUrl`/`wecomCheckinSession`/`wecomCheckinPage` + 类型;`checkin` 增严格链路参数 |
| 落地页 | `frontend/src/views/training/CheckinPage.vue` | 五态重构:OAuth 回跳换会话→复用登录持久化(签到即自动登录)→课程信息+身份确认行+倒计时→点击签到(工号+nonce)→成功后自动进课程详情;非企微环境引导重扫 |
| 讲师页 | `frontend/src/views/training/components/SignPanel.vue` | 10s 轻量轮询 sign-code 驱动惰性轮换(页面隐藏暂停);轮换倒计时展示;token 变化自动重绘二维码并提示 |
| 路由表 | `frontend/src/router/index.ts` | `trainingCheckin` 显式 `requiresAuth:false/requiresInit:false`(守卫对 undefined 仍拦截,必须显式 false) |
### 实施中的关键决策(与原方案差异)
1. **严格链路收口**:当天校验/工号+名单硬拒/nonce/时钟偏差仅在 `employee_no` 非空(新签到页)时生效 —— 代录补签常发生在非当天,须保持可用;既有登录态直签路径行为完全不变(名单外仍标 `not_in_roster` 进待复核)。
2. **补充规则落地**:签到录入工号必须在该场次「参加人员」名单中 → 扫码链路名单外**直接拒绝**(文案:"您不在该课程的『参加人员』名单中,请联系讲师或人事确认"),不再仅标记待复核。
3. **限流独立桶**:签到免登两个匿名入口用 `WecomCheckinRateLimit`(600/min/IP),不复用 auth 共享桶(30/min/IP)——教室几十人共享出口 IP,集中扫码会整批 429。
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`。
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 拦截器跳登录),**验证前必须重新构建部署前后端**。
+1 -1
View File
@@ -1,7 +1,7 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<title>AIDO</title> <title>和信智汇学院</title>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
+2 -2
View File
@@ -119,12 +119,12 @@ const persistOIDCLoginResponse = async (response: any) => {
if (result.ok) MessagePlugin.success(t('inviteRegister.joined')) if (result.ok) MessagePlugin.success(t('inviteRegister.joined'))
else MessagePlugin.warning(t('inviteRegister.invalidBody')) else MessagePlugin.warning(t('inviteRegister.invalidBody'))
// 会话已有效,无论 token 是否兑换成功都进入应用。 // 会话已有效,无论 token 是否兑换成功都进入应用。
router.replace('/platform/knowledge-bases') router.replace('/platform/creatChat')
return return
} }
await nextTick() await nextTick()
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace') router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
} }
const handleGlobalOIDCCallback = async () => { const handleGlobalOIDCCallback = async () => {
+3
View File
@@ -118,6 +118,8 @@ export interface UserInfo {
username: string username: string
email: string email: string
avatar?: string avatar?: string
// 姓名/显示名(工号式账号的 username 是工号,界面展示姓名用;未设置为空串)
display_name?: string
tenant_id: string tenant_id: string
can_access_all_tenants?: boolean can_access_all_tenants?: boolean
preferences?: UserPreferences preferences?: UserPreferences
@@ -158,6 +160,7 @@ export function userInfoFromApi(
username: u?.username || '', username: u?.username || '',
email: u?.email || '', email: u?.email || '',
avatar: u?.avatar, avatar: u?.avatar,
display_name: u?.display_name || '',
tenant_id: String(tid) || '', tenant_id: String(tid) || '',
can_access_all_tenants: u?.can_access_all_tenants === true, can_access_all_tenants: u?.can_access_all_tenants === true,
is_system_admin: u?.is_system_admin === true, is_system_admin: u?.is_system_admin === true,
+61
View File
@@ -1,4 +1,5 @@
import { get, post, put, del } from '@/utils/request' import { get, post, put, del } from '@/utils/request'
import type { WecomSyncSummary } from '@/api/training'
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。 // 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过 // 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
@@ -42,6 +43,8 @@ export interface OrgEmployee {
post: string post: string
lecturer_rate: number lecturer_rate: number
status: string status: string
/** 企微账号(OA 同步/绑定维护;列表 Select org_employees.* 随行返回)。 */
wecom_userid?: string
/** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */ /** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */
user_name?: string user_name?: string
dept_name?: string dept_name?: string
@@ -115,6 +118,64 @@ export interface OrgUpdateEmployee {
export const updateEmployee = (id: string, payload: OrgUpdateEmployee) => export const updateEmployee = (id: string, payload: OrgUpdateEmployee) =>
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}`, payload) put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}`, payload)
// ---- 职称角色 / 企微账号(自培训域迁入组织架构页;/org 域别名路由复用培训
// handler,角色绑定仍写 module_key='training';权限细控 HR/经理在 handler 内) ----
/** 设置员工职称角色(学员为全员隐式角色,由后端保留,前端保存时一并带上)。 */
export const updateOrgEmployeeRoles = (id: string, roles: string[]) =>
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/roles`, { roles })
/** 维护员工企微账号(培训提醒推送目标;留空即解绑)。 */
export const updateOrgEmployeeWecomUserid = (id: string, wecomUserid: string) =>
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/wecom-userid`, {
wecom_userid: wecomUserid,
})
/** 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式,预览只读)。 */
export const previewOrgWecomSync = () =>
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/preview`)
/** OA 同步写入(无冲突时才落库,返回写入统计)。 */
export const applyOrgWecomSync = () =>
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/apply`)
// ---- 归属空间收编(登录默认落点;后端 Owner 限定) ----
// 员工首登自动开通个人空间后,归属指针(users.tenant_id)停在个人空间,登录后
// 看到的组织架构/培训是个人空间那份空数据;收编把默认落点改回本空间,
// 成员关系与个人空间数据不变(可经空间切换器改回,非破坏性)。
/** 可收编成员:归属空间不在本空间的活跃成员。 */
export interface OrgAdoptableUser {
id: string
username: string
display_name: string
email: string
home_tenant_id: number
home_tenant_name: string
in_roster: boolean
}
/** 单条收编跳过记录(非本空间成员/停用/跨空间账号等,原因逐条回传)。 */
export interface OrgAdoptSkip {
user_id: string
username: string
display_name: string
reason: string
}
export interface OrgAdoptResult {
adopted: number
skipped: OrgAdoptSkip[]
}
/** 收编预览:归属空间不在本空间的活跃成员列表。 */
export const listAdoptableUsers = () =>
get<{ success: boolean; data: OrgAdoptableUser[] }>(`${base}/employees/adoptable`)
/** 批量收编:把成员的归属空间(登录默认落点)改为本空间。 */
export const adoptHomeTenant = (userIds: string[]) =>
post<{ success: boolean; data: OrgAdoptResult }>(`${base}/employees/adopt-home`, { user_ids: userIds })
// ---- 模块角色绑定 ---- // ---- 模块角色绑定 ----
export const listModuleMembers = (moduleKey: OrgModuleKey) => export const listModuleMembers = (moduleKey: OrgModuleKey) =>
+139 -10
View File
@@ -162,6 +162,8 @@ export interface TrainingDemand {
dept_id: string dept_id: string
submitter_id: string submitter_id: string
course_name: string course_name: string
/** 需求所填课程自动匹配的课程管理条目 id(000158:填报/导入时按名称精准匹配,未命中自动新增待核验课程) */
library_course_id?: string
/** 厂区(模板列:厂区,如 三厂) */ /** 厂区(模板列:厂区,如 三厂) */
plant: string plant: string
/** 培训分类(模板列:分类,如 知识/技能/安全) */ /** 培训分类(模板列:分类,如 知识/技能/安全) */
@@ -185,7 +187,7 @@ export interface TrainingDemand {
check_status: 'pending' | 'passed' | 'fixed' check_status: 'pending' | 'passed' | 'fixed'
check_msg: string check_msg: string
status: string status: string
/** 联查展示字段:部门名称/讲师姓名/创建人姓名(提报人,联查 users 只读) */ /** 部门名称(列表联查 org_depts 只读;导入载荷另携带 Excel「部门」列原始值,000158 后端据此做导入人部门归属校验) */
dept_name?: string dept_name?: string
lecturer_name?: string lecturer_name?: string
submitter_name?: string submitter_name?: string
@@ -324,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(经理确认自动转月度计划时回填,溯源用) */
@@ -423,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-####,创建/导入时由服务端生成,列表/详情展示) */
@@ -435,8 +457,12 @@ 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
/** 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存) */ /** 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存) */
category: string category: string
/** 类型:required 必修课 / elective 选修课 */ /** 类型:required 必修课 / elective 选修课 */
@@ -454,8 +480,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 已确认;发布前必须已确认 */
@@ -472,6 +500,8 @@ export interface TrainingLibraryCourse {
creator_id?: string creator_id?: string
/** 创建人姓名(联查 users 只读;导入/新增时落 creator_id 后带出) */ /** 创建人姓名(联查 users 只读;导入/新增时落 creator_id 后带出) */
creator_name?: string creator_name?: string
/** 关联题库数(联查只读;列表「试题」有/无展示) */
question_bank_count?: number
created_at?: string created_at?: string
updated_at?: string updated_at?: string
} }
@@ -493,9 +523,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>[]) =>
@@ -520,9 +554,16 @@ 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, mid?: string) =>
post<{ success: boolean; data: TrainingLibraryCourse }>(
`${base}/course-library/${enc(id)}/material/remove`,
mid ? { mid } : {},
)
export const listSessions = (query?: ListQuery) => export const listSessions = (query?: ListQuery) =>
get<{ success: boolean; data: TrainingCourseSession[] }>(`${base}/sessions`, { params: query }) get<{ success: boolean; data: TrainingCourseSession[] }>(`${base}/sessions`, { params: query })
@@ -637,13 +678,97 @@ export const createSignCode = (
export const getSignCode = (sessionId: string) => export const getSignCode = (sessionId: string) =>
get<{ success: boolean; data: TrainingSignCode }>(`${base}/sessions/${enc(sessionId)}/sign-code`) get<{ success: boolean; data: TrainingSignCode }>(`${base}/sessions/${enc(sessionId)}/sign-code`)
export const checkin = (token: string, lat = 0, lng = 0, channel = 'wecom_scan', memberId = '') => // 企微扫码签到免登(2026-11 需求):落地页免登与自动登录一条链路。
// checkin-auth 匿名(授权链接);checkin-session 匿名(code 换会话+页面数据,
// 响应与 /auth/login 同构,落地页复用登录持久化);checkin-page 登录态
// (PC 讲师自测/企微内已有会话)。
export const getCheckinAuthUrl = (token: string, redirectUri = '') =>
get<{ success: boolean; data: { authorize_url: string } }>(`${base}/wecom/checkin-auth`, {
params: { token, redirect_uri: redirectUri || undefined },
})
export interface WecomCheckinCourseInfo {
course_id: string
course_name: string
lecturer_name: string
start_at: string | null
end_at: string | null
location: string
status: string
can_sign_today: boolean
}
export interface WecomCheckinPageData {
member?: { employee_no: string; user_name?: string; post?: string; dept_name?: string }
course?: WecomCheckinCourseInfo
course_id: string
session_id: string
sign_expire_at: string | null
in_roster: boolean
already_signed: boolean
}
export interface WecomCheckinSessionData extends WecomCheckinPageData {
success?: boolean
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 }>
}
export const wecomCheckinSession = (code: string, state: string) =>
post<{ success: boolean; data: WecomCheckinSessionData }>(`${base}/wecom/checkin-session`, { code, state })
export const wecomCheckinPage = (token: string) =>
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 = (
token: string,
lat = 0,
lng = 0,
channel = 'wecom_scan',
memberId = '',
opts?: { employee_no?: string; nonce?: string; client_ts?: number },
) =>
post<{ success: boolean; data: TrainingSignRecord }>(`${base}/sign-records/checkin`, { post<{ success: boolean; data: TrainingSignRecord }>(`${base}/sign-records/checkin`, {
token, token,
lat, lat,
lng, lng,
channel, channel,
member_id: memberId || undefined, member_id: memberId || undefined,
// 2026-11 扫码严格链路:工号(须在参加人员名单)+ 随机时间戳防重放。
employee_no: opts?.employee_no || undefined,
nonce: opts?.nonce || undefined,
client_ts: opts?.client_ts || undefined,
}) })
export const listSignRecords = (sessionId: string) => export const listSignRecords = (sessionId: string) =>
@@ -968,6 +1093,10 @@ export const saveLearningProgress = (taskId: string, materialId: string, positio
export const listMyLearningTasks = () => export const listMyLearningTasks = () =>
get<{ success: boolean; data: LearningTask[] }>(`${base}/learning-tasks`) get<{ success: boolean; data: LearningTask[] }>(`${base}/learning-tasks`)
/** 我经场次学员名单报名的课程 id 去重集合(我的培训「我参加」判定) */
export const listMyEnrolledCourseIds = () =>
get<{ success: boolean; data: string[] }>(`${base}/my/enrolled-course-ids`)
/** 管理端课程学习情况行(全员学习任务 + 员工展示字段) */ /** 管理端课程学习情况行(全员学习任务 + 员工展示字段) */
export interface CourseLearningTask extends LearningTask { export interface CourseLearningTask extends LearningTask {
employee_no?: string employee_no?: string
@@ -1310,7 +1439,7 @@ export const NOTIFY_TEXT_TEMPLATES_RULE_KEY = 'notify_text_templates'
export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集' export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集'
export const DEFAULT_DEMAND_COLLECT_CONTENT = export const DEFAULT_DEMAND_COLLECT_CONTENT =
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' + '请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。' '可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录和信智汇学院 → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/ /** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */ * 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
+15 -7
View File
@@ -8,12 +8,12 @@
<span v-else class="avatar-placeholder">{{ userInitial }}</span> <span v-else class="avatar-placeholder">{{ userInitial }}</span>
</div> </div>
<div v-if="!showCollapsedLayout" class="user-info"> <div v-if="!showCollapsedLayout" class="user-info">
<!-- 多空间 / superuser:首行空间名,次行 username · 角色。单空间:昵称 + 邮箱。 --> <!-- 多空间 / superuser:首行空间名,次行 姓名(未设置回落账号) · 角色。单空间:账号 + 姓名(未设置回落邮箱)。 -->
<template v-if="showTenantIdentityLine"> <template v-if="showTenantIdentityLine">
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div> <div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
<div class="user-tenant-meta"> <div class="user-tenant-meta">
<span v-if="userName && userName !== activeTenantName" class="user-tenant-meta-name">{{ userName }}</span> <span v-if="userDisplayLabel && userDisplayLabel !== activeTenantName" class="user-tenant-meta-name">{{ userDisplayLabel }}</span>
<span v-if="(userName && userName !== activeTenantName) && currentRoleLabel" <span v-if="(userDisplayLabel && userDisplayLabel !== activeTenantName) && currentRoleLabel"
class="user-tenant-meta-sep">·</span> class="user-tenant-meta-sep">·</span>
<t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" /> <t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" />
<span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span> <span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span>
@@ -21,7 +21,7 @@
</template> </template>
<template v-else> <template v-else>
<div class="user-name">{{ userName }}</div> <div class="user-name">{{ userName }}</div>
<div class="user-email">{{ userEmail }}</div> <div class="user-email">{{ userDisplayName }}</div>
</template> </template>
</div> </div>
</div> </div>
@@ -67,7 +67,7 @@
</button> </button>
</t-tooltip> </t-tooltip>
</div> </div>
<span v-if="userEmail" class="dropdown-user-email">{{ userEmail }}</span> <span v-if="userDisplayName" class="dropdown-user-email">{{ userDisplayName }}</span>
</div> </div>
</div> </div>
@@ -198,6 +198,7 @@ const menuVisible = ref(false)
const userInfo = computed(() => ({ const userInfo = computed(() => ({
username: authStore.user?.username || t('common.defaultUser'), username: authStore.user?.username || t('common.defaultUser'),
email: authStore.user?.email || 'user@example.com', email: authStore.user?.email || 'user@example.com',
displayName: authStore.user?.display_name || '',
avatar: authStore.user?.avatar || '', avatar: authStore.user?.avatar || '',
})) }))
@@ -205,9 +206,16 @@ const userName = computed(() => userInfo.value.username)
const userEmail = computed(() => userInfo.value.email) const userEmail = computed(() => userInfo.value.email)
const userAvatar = computed(() => userInfo.value.avatar) const userAvatar = computed(() => userInfo.value.avatar)
// 用户名首字母(用于无头像时显示) // 侧栏第二行:工号式账号的 username 是工号,优先展示姓名;未设置姓名时回落邮箱
const userDisplayName = computed(() => userInfo.value.displayName || userInfo.value.email)
// 多空间身份行的姓名标签:优先姓名,未设置姓名时回落账号(工号/用户名)
const userDisplayLabel = computed(() => userInfo.value.displayName || userInfo.value.username)
// 用户名首字母(用于无头像时显示):优先取姓名首字(如「刘义亮」→「刘」),
// 未设置姓名时回落账号首字符
const userInitial = computed(() => { const userInitial = computed(() => {
return userName.value.charAt(0).toUpperCase() return userDisplayLabel.value.charAt(0).toUpperCase()
}) })
// 切换菜单显示 // 切换菜单显示
+9 -7
View File
@@ -1,5 +1,7 @@
// ===== AIDO 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 ===== // ===== 和信智汇学院 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入 // 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入。
// 品牌名由「AIDO」更名而来:中文六个字,字号/字距相应收窄以适配
// 260px 展开侧栏(logo 与搜索/折叠图标同行)与登录页左上角。
.aido-logo { .aido-logo {
position: relative; position: relative;
display: inline-flex; display: inline-flex;
@@ -16,12 +18,12 @@
} }
&__text { &__text {
font-family: 'Trebuchet MS', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif; font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', sans-serif;
font-size: 27px; font-size: 19px;
line-height: 1.15; line-height: 1.15;
font-weight: 800; font-weight: 700;
font-style: italic; white-space: nowrap;
letter-spacing: 2.5px; letter-spacing: 1px;
background-image: background-image:
linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.85) 50%, rgba(255, 255, 255, 0) 58%), linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.85) 50%, rgba(255, 255, 255, 0) 58%),
linear-gradient(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%); linear-gradient(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%);
+11 -11
View File
@@ -5,9 +5,9 @@
<div class="aside_rail"> <div class="aside_rail">
<!-- 展开时:Logo + 搜索/折叠按钮同行 --> <!-- 展开时:Logo + 搜索/折叠按钮同行 -->
<div class="logo_row" v-if="!uiStore.sidebarCollapsed"> <div class="logo_row" v-if="!uiStore.sidebarCollapsed">
<div class="logo_box" @click="router.push('/platform/knowledge-bases')" style="cursor: pointer;"> <div class="logo_box" @click="router.push('/platform/creatChat')" style="cursor: pointer;">
<span class="aido-logo" aria-label="AIDO" title="AIDO"> <span class="aido-logo" aria-label="和信智汇学院" title="和信智汇学院">
<span class="aido-logo__text">AIDO</span> <span class="aido-logo__text">和信智汇学院</span>
<span class="aido-logo__dot"></span> <span class="aido-logo__dot"></span>
</span> </span>
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup> <sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
@@ -605,12 +605,12 @@ 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);
// 末位固定追加「配置中心」「职称角色」「组织架构」;「共享空间」还原至最底 // 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐) // (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
// 职称角色(000159):自「企业培训」分组迁入,置于配置中心之后 // 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由
const MEMBERS_TOOL_ITEM: MenuItem = { title: '职称角色', icon: 'training', path: '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, MEMBERS_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])]; return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
}); });
// 菜单图标统一映射:顶层项与「更多工具」子项共用 // 菜单图标统一映射:顶层项与「更多工具」子项共用
@@ -645,9 +645,9 @@ const TRAINING_TABS: { key: string; title: string }[] = [
]; ];
const TRAINING_GROUP_TITLE = '企业培训'; const TRAINING_GROUP_TITLE = '企业培训';
// 分组展开状态(记忆用户偏好,默认展开),交互与「更多工具」一致 // 分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
const TRAINING_OPEN_KEY = 'academy_training_open'; const TRAINING_OPEN_KEY = 'academy_training_open';
const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) !== 'false'); const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) === 'true');
const toggleTraining = () => { const toggleTraining = () => {
trainingOpen.value = !trainingOpen.value; trainingOpen.value = !trainingOpen.value;
localStorage.setItem(TRAINING_OPEN_KEY, String(trainingOpen.value)); localStorage.setItem(TRAINING_OPEN_KEY, String(trainingOpen.value));
@@ -669,9 +669,9 @@ const isTrainingTabActive = (tab: string): boolean => {
return (String(route.params.tab || 'dashboard')) === tab; return (String(route.params.tab || 'dashboard')) === tab;
}; };
// 「更多工具」分组展开状态(记忆用户偏好,默认展开) // 「更多工具」分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
const MORE_TOOLS_OPEN_KEY = 'academy_moretools_open'; const MORE_TOOLS_OPEN_KEY = 'academy_moretools_open';
const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) !== 'false'); const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) === 'true');
const toggleMoreTools = () => { const toggleMoreTools = () => {
moreToolsOpen.value = !moreToolsOpen.value; moreToolsOpen.value = !moreToolsOpen.value;
localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value)); localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value));
+1 -1
View File
@@ -2970,7 +2970,7 @@ export default {
haveAccount: 'Already have an account?', haveAccount: 'Already have an account?',
backToLogin: 'Back to Login', backToLogin: 'Back to Login',
loginHint: 'Sign in to continue, or create an account below if this is your first time.', loginHint: 'Sign in to continue, or create an account below if this is your first time.',
firstTime: 'New to AIDO?', firstTime: 'New to 和信智汇学院?',
registerSuccess: 'Registration successful. Please sign in', registerSuccess: 'Registration successful. Please sign in',
registerFailed: 'Registration failed', registerFailed: 'Registration failed',
subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade', subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade',
+1 -1
View File
@@ -2970,7 +2970,7 @@ export default {
haveAccount: 'すでにアカウントをお持ちですか?', haveAccount: 'すでにアカウントをお持ちですか?',
backToLogin: 'ログインに戻る', backToLogin: 'ログインに戻る',
loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。', loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。',
firstTime: 'AIDOは初めてですか?', firstTime: '和信智汇学院は初めてですか?',
registerSuccess: '登録が完了しました。ログインしてください', registerSuccess: '登録が完了しました。ログインしてください',
registerFailed: '登録に失敗しました', registerFailed: '登録に失敗しました',
subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード', subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード',
+1 -1
View File
@@ -6262,7 +6262,7 @@ export default {
haveAccount: '이미 계정이 있으신가요?', haveAccount: '이미 계정이 있으신가요?',
backToLogin: '로그인으로 돌아가기', backToLogin: '로그인으로 돌아가기',
loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.', loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.',
firstTime: 'AIDO가 처음이신가요?', firstTime: '和信智汇学院이 처음이신가요?',
registerSuccess: '가입이 완료되었습니다. 로그인해주세요', registerSuccess: '가입이 완료되었습니다. 로그인해주세요',
registerFailed: '가입 실패', registerFailed: '가입 실패',
subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드', subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드',
+1 -1
View File
@@ -6262,7 +6262,7 @@ export default {
haveAccount: 'Уже есть аккаунт?', haveAccount: 'Уже есть аккаунт?',
backToLogin: 'Вернуться ко входу', backToLogin: 'Вернуться ко входу',
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.', loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
firstTime: 'Впервые в AIDO?', firstTime: 'Впервые в 和信智汇学院?',
registerSuccess: 'Регистрация завершена. Войдите в систему', registerSuccess: 'Регистрация завершена. Войдите в систему',
registerFailed: 'Ошибка регистрации', registerFailed: 'Ошибка регистрации',
subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ', subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ',
+2 -2
View File
@@ -5949,7 +5949,7 @@ export default {
} }
}, },
createChat: { createChat: {
title: 'Hi,我是 Academy,让你的知识触手可及', title: 'Hi,我是小和,让你的知识触手可及',
newSessionTitle: '新会话', newSessionTitle: '新会话',
openProject: '选择项目', openProject: '选择项目',
clearProject: '取消绑定', clearProject: '取消绑定',
@@ -6263,7 +6263,7 @@ export default {
haveAccount: '已有账户?', haveAccount: '已有账户?',
backToLogin: '返回登录', backToLogin: '返回登录',
loginHint: '登录以继续使用;首次使用请在下方创建账户。', loginHint: '登录以继续使用;首次使用请在下方创建账户。',
firstTime: '首次使用 AIDO?', firstTime: '首次使用 和信智汇学院?',
registerSuccess: '注册成功,请登录', registerSuccess: '注册成功,请登录',
registerFailed: '注册失败', registerFailed: '注册失败',
subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级', subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级',
+1 -1
View File
@@ -6263,7 +6263,7 @@ export default {
haveAccount: '已有帳戶?', haveAccount: '已有帳戶?',
backToLogin: '返回登入', backToLogin: '返回登入',
loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。', loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。',
firstTime: '首次使用 AIDO?', firstTime: '首次使用 和信智汇学院?',
registerSuccess: '註冊成功,請登入', registerSuccess: '註冊成功,請登入',
registerFailed: '註冊失敗', registerFailed: '註冊失敗',
subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級', subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級',
+37 -15
View File
@@ -27,6 +27,7 @@ function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
to.path === '/' || to.path === '/' ||
to.path === '/platform' || to.path === '/platform' ||
to.path === '/platform/knowledge-bases' || to.path === '/platform/knowledge-bases' ||
to.path === '/platform/creatChat' ||
to.name === 'knowledgeBaseList' to.name === 'knowledgeBaseList'
) )
} }
@@ -46,7 +47,8 @@ const router = createRouter({
routes: [ routes: [
{ {
path: "/", path: "/",
redirect: "/platform/knowledge-bases", // 登录用户默认打开 AI 对话页(首页口径,与登录成功跳转一致)
redirect: "/platform/creatChat",
}, },
{ {
path: "/login", path: "/login",
@@ -54,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",
@@ -94,7 +107,7 @@ const router = createRouter({
{ {
path: "/platform", path: "/platform",
name: "Platform", name: "Platform",
redirect: "/platform/knowledge-bases", redirect: "/platform/creatChat",
component: () => import("../views/platform/index.vue"), component: () => import("../views/platform/index.vue"),
meta: { requiresInit: true, requiresAuth: true }, meta: { requiresInit: true, requiresAuth: true },
children: [ children: [
@@ -156,12 +169,18 @@ const router = createRouter({
meta: { requiresInit: true, requiresAuth: true } meta: { requiresInit: true, requiresAuth: true }
}, },
{ {
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/职称角色/配置中心) // 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/配置中心)
// 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。 // 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。
path: "training", path: "training",
name: "training", name: "training",
redirect: "/platform/training/dashboard" redirect: "/platform/training/dashboard"
}, },
{
// 职称角色页已并入「组织架构」页维护(员工/角色/企微账号一处维护),
// 旧链接与书签兜底重定向。
path: "training/members",
redirect: "/platform/org-center"
},
{ {
path: "training/:tab", path: "training/:tab",
name: "trainingTab", name: "trainingTab",
@@ -176,13 +195,16 @@ 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 }
}, },
{ {
// 学员扫码签到页:培训签到页二维码落地页,携 token 自动定位并签到(需登录态)。 // 旧平台内签到路径兼容重定向(2026-11-25 签到页迁移为独立手机端 H5):
path: "training/checkin/:token", // 已投屏/已分发的旧二维码短窗口内仍可扫;携 query 重定向,OAuth 回跳
name: "trainingCheckin", // 参数(code/state)不丢。
component: () => import("../views/training/CheckinPage.vue"), path: "training/checkin/:token",
meta: { requiresInit: true, requiresAuth: true } redirect: (to) => ({
}, path: `/m/training/checkin/${to.params.token}`,
query: to.query
})
},
{ {
// 组织架构:租户级共享组织架构(部门 + 员工档案), // 组织架构:租户级共享组织架构(部门 + 员工档案),
// 业务模块(企业培训等)按需引用,部门岗位只维护一份。 // 业务模块(企业培训等)按需引用,部门岗位只维护一份。
@@ -368,7 +390,7 @@ router.beforeEach(async (to, from, next) => {
} }
} }
if (authStore.hasValidTenant) { if (authStore.hasValidTenant) {
next('/platform/knowledge-bases') next('/platform/creatChat')
} else { } else {
next() next()
} }
@@ -377,9 +399,9 @@ router.beforeEach(async (to, from, next) => {
// 如果访问的是登录页面或初始化页面,直接放行 // 如果访问的是登录页面或初始化页面,直接放行
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) { if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
// 如果已登录用户访问登录页面,重定向到知识库列表页面 // 如果已登录用户访问登录页面,重定向到首页(AI 对话)
if (to.path === '/login' && authStore.isLoggedIn) { if (to.path === '/login' && authStore.isLoggedIn) {
next(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace') next(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
return return
} }
next() next()
@@ -431,7 +453,7 @@ router.beforeEach(async (to, from, next) => {
const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined
if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) { if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) {
MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable')) MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable'))
next('/platform/knowledge-bases') next('/platform/creatChat')
return return
} }
@@ -441,7 +463,7 @@ router.beforeEach(async (to, from, next) => {
// the bounce. This is UI-only; the server enforces the real check. // the bounce. This is UI-only; the server enforces the real check.
if (to.meta.requiresSystemAdmin === true) { if (to.meta.requiresSystemAdmin === true) {
if (!authStore.isSystemAdmin) { if (!authStore.isSystemAdmin) {
next('/platform/knowledge-bases') next('/platform/creatChat')
return return
} }
} }
+63 -4
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: '', file_size: 0, 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: '', file_size: 0, 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, 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-####)
@@ -313,8 +315,65 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
if (url.includes('/question-banks/') && url.includes('/questions')) { if (url.includes('/question-banks/') && url.includes('/questions')) {
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')) {
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
if (course) {
const list = course.materials || []
list.pop()
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'
}
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) {
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.materials = [...(course.materials || []), entry]
course.file_name = entry.name
course.file_size = entry.size
course.verify_status = 'pending'
}
return ok(course || { id: `c-new-${Date.now()}` })
}
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()}` })
} }
+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)
}
@@ -3021,8 +3021,11 @@ const removeStarterSuggestion = (index: number) => {
formData.value.config.question_suggestions.starters.items.splice(index, 1); formData.value.config.question_suggestions.starters.items.splice(index, 1);
}; };
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
// 仅在字段为空时补值,绝不覆盖用户已选;编辑态补默认可修复存量空模型智能体,
// 免去「模型必填」手动配置(与后端 create 兜底同规则)。
const applyDefaultModelsIfEmpty = () => { const applyDefaultModelsIfEmpty = () => {
if (props.mode !== 'create' || !formData.value) return if (!formData.value) return
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA') const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
const rerankModelId = selectInitialModelId(allModels.value, 'Rerank') const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
if (!formData.value.config.model_id && chatModelId) { if (!formData.value.config.model_id && chatModelId) {
@@ -3698,6 +3701,8 @@ watch(() => props.visible, async (val) => {
// Display inherited defaults for all agents without persisting a copy. // Display inherited defaults for all agents without persisting a copy.
fillBuiltinAgentDefaults(); fillBuiltinAgentDefaults();
void loadAgentIntegrationCounts(agentData.id); void loadAgentIntegrationCounts(agentData.id);
// 编辑态同样补默认模型(仅空字段):存量空模型智能体不再被「模型必填」卡住
applyDefaultModelsIfEmpty()
} else { } else {
// 创建新智能体,使用系统默认值 // 创建新智能体,使用系统默认值
storedToolNames.value = []; storedToolNames.value = [];
+23 -5
View File
@@ -97,8 +97,8 @@
<!-- Logo - Top Left --> <!-- Logo - Top Left -->
<a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')"> <a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')">
<span class="aido-logo" aria-label="AIDO"> <span class="aido-logo" aria-label="和信智汇学院">
<span class="aido-logo__text">AIDO</span> <span class="aido-logo__text">和信智汇学院</span>
<span class="aido-logo__dot"></span> <span class="aido-logo__dot"></span>
</span> </span>
</a> </a>
@@ -611,7 +611,7 @@ const persistLoginResponse = async (response: any, skipRedirect = false) => {
await authStore.refreshFromAuthMe() await authStore.refreshFromAuthMe()
await nextTick() await nextTick()
if (skipRedirect) return if (skipRedirect) return
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace') router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
} }
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback` const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
@@ -694,7 +694,7 @@ const acceptAndEnter = async (token: string) => {
} finally { } finally {
loading.value = false loading.value = false
await nextTick() await nextTick()
router.replace('/platform/knowledge-bases') router.replace('/platform/creatChat')
} }
} }
@@ -852,7 +852,7 @@ onMounted(async () => {
} }
if (authStore.isLoggedIn) { if (authStore.isLoggedIn) {
router.replace('/platform/knowledge-bases') router.replace('/platform/creatChat')
return return
} }
@@ -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 {
@@ -889,8 +889,11 @@ const kbCreateNeedsEmbedding = computed(() => {
return Boolean(s?.vectorEnabled || s?.keywordEnabled) return Boolean(s?.vectorEnabled || s?.keywordEnabled)
}) })
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
// 仅在字段为空时补值,不覆盖用户已选;与后端 CreateKnowledgeBase 的默认兜底
// 同规则,编辑态补默认可修复存量未绑模型的知识库。
const applyDefaultModelsIfEmpty = () => { const applyDefaultModelsIfEmpty = () => {
if (!formData.value || editorMode.value !== 'create') return if (!formData.value) return
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA') const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding') const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding')
if (!formData.value.modelConfig.llmModelId && chatModelId) { if (!formData.value.modelConfig.llmModelId && chatModelId) {
@@ -1936,6 +1939,8 @@ watch(() => props.visible, async (newVal) => {
// 根据模式加载数据 // 根据模式加载数据
if (props.mode === 'edit' && targetKbId) { if (props.mode === 'edit' && targetKbId) {
await loadKBData(targetKbId, generation) await loadKBData(targetKbId, generation)
// 编辑态同样补默认模型(仅空字段):存量未绑模型的知识库不再要求手动选择
applyDefaultModelsIfEmpty()
} else { } else {
// 创建模式:初始化空表单,并预填空间默认存储引擎 // 创建模式:初始化空表单,并预填空间默认存储引擎
formData.value = initFormData(props.initialType || 'document') formData.value = initFormData(props.initialType || 'document')
+482 -32
View File
@@ -21,7 +21,7 @@
<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"> <t-table :data="pagedDepts" :columns="deptColumns" row-key="id" size="small">
<template #op="{ row }"> <template #op="{ row }">
<div class="op-group"> <div class="op-group">
<t-button variant="text" theme="primary" size="small" @click="onEditDept(row)">修改</t-button> <t-button variant="text" theme="primary" size="small" @click="onEditDept(row)">修改</t-button>
@@ -29,23 +29,56 @@
</div> </div>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(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">
<div class="panel-box__header"> <div class="panel-box__header">
<span class="panel-box__title">员工档案</span> <span class="panel-box__title">员工档案</span>
<div style="display: flex; gap: 8px"> <!-- 自「职称角色」页迁入:提示 + OA 同步入口(管理角色可见) -->
<div class="org-employees__actions">
<span class="org-employees__hint">员工与部门在本页统一维护,职称角色与企微账号可直接配置</span>
<t-input
v-model="keyword"
class="org-employees__search"
clearable
placeholder="按姓名 / 工号 / 部门查找"
@enter="loadEmployees"
@clear="loadEmployees"
>
<template #prefixIcon><t-icon name="search" /></template>
</t-input>
<t-button
v-if="canManage"
variant="outline"
theme="primary"
:loading="syncing"
class="oa-sync-btn"
@click="onPreviewSync"
>
从OA同步企微账号
</t-button>
<!-- 收编归属空间:仅空间 Owner 可见/可操作(后端路由 Owner 限定),
把登录落在个人空间的成员默认落点改回本空间 -->
<t-button v-if="canAdopt" variant="outline" @click="openAdopt">收编到本空间</t-button>
<t-button variant="outline" @click="openPicker">从平台用户添加</t-button> <t-button variant="outline" @click="openPicker">从平台用户添加</t-button>
<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"> <t-table :data="pagedEmployees" :columns="employeeColumns" row-key="id" size="small" :loading="loading">
<template #user_name="{ row }"> <template #user_name="{ row }">
<t-tooltip :content="employeeName(row)" :disabled="!employeeName(row)"> <t-tooltip :content="employeeName(row)" :disabled="!employeeName(row)">
<span class="employee-name">{{ employeeName(row) || '-' }}</span> <span class="employee-name">{{ employeeName(row) || '-' }}</span>
</t-tooltip> </t-tooltip>
</template> </template>
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template> <template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
<template #wecom_userid="{ row }">
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
</template>
<template #roles="{ row }">
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
</template>
<template #status="{ row }"> <template #status="{ row }">
<t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag> <t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag>
<t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag> <t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag>
@@ -54,9 +87,13 @@
<template #op="{ row }"> <template #op="{ row }">
<div class="op-group"> <div class="op-group">
<t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button> <t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button>
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
</div> </div>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(000164):默认每页 15 条 -->
<TrainingPagination v-model:current="employeePage" v-model:page-size="employeePageSize" :total="employeeTotal" />
</div> </div>
</div> </div>
</div> </div>
@@ -150,6 +187,106 @@
<t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button> <t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button>
</template> </template>
</t-dialog> </t-dialog>
<!-- 绑定企微账号(培训提醒推送目标;自职称角色页迁入) -->
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
<template #footer>
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
</template>
</t-dialog>
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
<template v-if="syncSummary">
<div class="sync-stats">
<span>本地员工 {{ syncSummary.local_candidates }}</span>
<span>OA 命中 {{ syncSummary.local_matched }}</span>
<span>已一致 {{ syncSummary.already_bound }}</span>
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
</div>
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
{{ cf.employee_no }} {{ cf.user_name || '' }}:
{{ conflictText(cf) }}
</div>
</div>
<div v-if="syncSummary.would_update" class="sync-section">
<div class="sync-section__title">将写入(最多展示 20 条)</div>
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
</div>
</div>
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
无需更新:绑定已一致或 OA 无匹配数据。
</div>
<div class="sync-footer">
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
theme="primary" :loading="syncing" @click="onApplySync">
确认写入
</t-button>
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
</div>
</template>
</t-dialog>
<!-- 设置职称角色(自职称角色页迁入;绑定写 module_key='training') -->
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
<t-select v-model="roleSelection" multiple style="width: 100%">
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
</t-select>
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
<template #footer>
<t-button theme="primary" :loading="savingRoles" @click="onSaveRoles">保存</t-button>
</template>
</t-dialog>
<!-- 收编到本空间:把登录落在个人空间的成员的默认落点改回本空间。
预览(归属空间不在本空间的活跃成员)→ 确认收编,与 OA 同步同两段式交互 -->
<t-dialog v-model:visible="adoptVisible" header="收编成员到本空间" width="680" :footer="false">
<div class="form-hint adopt-hint">
名单为「归属空间不在本空间」的活跃成员(首次登录自动开通个人空间后,登录会落进个人空间,看不到本空间维护的组织架构与培训数据)。
收编后其默认登录空间改为本空间,下次登录起直接进入本空间;成员关系、角色与个人空间数据均不变,成员仍可随时用左下角空间切换器改回。
</div>
<template v-if="adoptLoaded">
<div v-if="!adoptList.length" class="sync-section">
没有可收编成员:所有成员的登录默认空间都已指向本空间。
</div>
<template v-else>
<t-table
:data="adoptList"
:columns="adoptColumns"
row-key="id"
size="small"
max-height="360"
>
<template #display_name="{ row }">{{ row.display_name || '-' }}</template>
<template #home="{ row }">
{{ row.home_tenant_name || (row.home_tenant_id ? `空间 ${row.home_tenant_id}` : '无归属空间') }}
</template>
<template #in_roster="{ row }">
<t-tag v-if="row.in_roster" theme="success" variant="light" size="small">在名册</t-tag>
<t-tag v-else theme="default" variant="light" size="small">未入册</t-tag>
</template>
</t-table>
<div class="sync-footer">
<t-button variant="outline" @click="adoptVisible = false">关闭</t-button>
<t-button theme="primary" :loading="adopting" @click="onAdopt">
全部收编({{ adoptList.length }})
</t-button>
</div>
</template>
</template>
</t-dialog>
</div> </div>
</template> </template>
@@ -157,26 +294,50 @@
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
import { import {
adoptHomeTenant,
applyOrgWecomSync,
deleteDept, deleteDept,
importEmployees, importEmployees,
listAdoptableUsers,
listDepts, listDepts,
listEmployees, listEmployees,
listPlatformUsers, listPlatformUsers,
ORG_MODULE_TRAINING,
previewOrgWecomSync,
saveDept, saveDept,
updateEmployee, updateEmployee,
updateOrgEmployeeRoles,
updateOrgEmployeeWecomUserid,
type OrgAdoptableUser,
type OrgDept, type OrgDept,
type OrgEmployee, type OrgEmployee,
type OrgPlatformUser, type OrgPlatformUser,
} from '@/api/org-center' } from '@/api/org-center'
import { unwrap } from '@/api/training' import {
expandRoles,
fetchRoleDict,
getMyProfile,
roleLabelOf,
unwrap,
type TrainingRoleDef,
type WecomSyncConflict,
type WecomSyncSummary,
} from '@/api/training'
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 loading = ref(false) const loading = ref(false)
const saving = ref(false) const saving = ref(false)
const depts = ref<OrgDept[]>([]) const depts = ref<OrgDept[]>([])
const employees = ref<OrgEmployee[]>([]) const employees = ref<OrgEmployee[]>([])
const platformUsers = ref<OrgPlatformUser[]>([]) const platformUsers = ref<OrgPlatformUser[]>([])
// 员工查找(需求:按名称/工号/部门);keyword 走后端 ListEmployees 的过滤。
const keyword = ref('')
const deptFormVisible = ref(false) const deptFormVisible = ref(false)
const importVisible = ref(false) const importVisible = ref(false)
// id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。 // id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。
@@ -193,23 +354,195 @@ const pickerPost = ref('')
const employeeFormVisible = ref(false) const employeeFormVisible = ref(false)
const employeeForm = ref({ id: '', user_name: '', employee_no: '', dept_id: '', post: '', status: 'active' }) const employeeForm = ref({ id: '', user_name: '', employee_no: '', dept_id: '', post: '', status: 'active' })
const deptColumns = [ // ---- 职称角色 / 企微账号(自培训域「职称角色」页迁入) ----
{ colKey: 'name', title: '部门名称' },
{ colKey: 'code', title: '编码', width: 140 }, // 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
// 窄屏下列宽超出面板时操作列随滚动固定在右侧,保证可见可点 const roleDict = ref<TrainingRoleDef[]>([])
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' }, // 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护)
const rawRoles = ref<string[]>([])
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
const canManage = computed(
() => authStore.hasRole('admin') || myRoles.value.some((r) => r === 'hr' || r === 'exec'),
)
const rolesVisible = ref(false)
const activeEmployee = ref<OrgEmployee | null>(null)
const roleSelection = ref<string[]>([])
const savingRoles = ref(false)
const wecomVisible = ref(false)
const activeWecomEmployee = ref<OrgEmployee | null>(null)
const wecomInput = ref('')
const savingWecom = ref(false)
// OA 同步(工号 → 企微 userid,预览→写入两段式)
const syncVisible = ref(false)
const syncing = ref(false)
const syncSummary = ref<WecomSyncSummary | null>(null)
const conflictText = (cf: WecomSyncConflict) => {
switch (cf.reason) {
case 'duplicate_workcode_in_oa':
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
case 'bound_to_different_userid':
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
case 'userid_occupied':
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
default:
return cf.reason
}
}
const onPreviewSync = async () => {
syncing.value = true
try {
const res = await previewOrgWecomSync()
syncSummary.value = unwrap(res) ?? null
syncVisible.value = true
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
} finally {
syncing.value = false
}
}
const onApplySync = async () => {
syncing.value = true
try {
const res = await applyOrgWecomSync()
const summary = unwrap(res)
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
syncVisible.value = false
loadEmployees()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '写入失败')
} finally {
syncing.value = false
}
}
// ---- 收编到本空间(归属空间=登录默认落点;后端 Owner 限定) ----
// 仅空间 Owner 可见(与后端 g.Owner() 路由口径对齐;localStorage 只是渲染参考,
// 实际权限以服务端为准,越权点击会收到 403)。
const canAdopt = computed(() => authStore.hasRole('owner'))
const adoptVisible = ref(false)
const adoptLoaded = ref(false)
const adopting = ref(false)
const adoptList = ref<OrgAdoptableUser[]>([])
const adoptColumns = [
{ colKey: 'username', title: '工号', width: 100 },
{ colKey: 'display_name', title: '姓名', width: 110 },
{ colKey: 'email', title: '邮箱', minWidth: 160, ellipsis: true },
{ colKey: 'home', title: '当前归属空间(登录落点)', width: 180 },
{ colKey: 'in_roster', title: '名册', width: 80 },
] ]
const employeeColumns = [ const openAdopt = async () => {
{ colKey: 'employee_no', title: '工号', width: 90 }, adoptVisible.value = true
{ colKey: 'user_name', title: '姓名' }, adoptLoaded.value = false
{ colKey: 'dept_name', title: '部门', width: 110 }, adoptList.value = []
{ colKey: 'post', title: '岗位', width: 140 }, try {
{ colKey: 'status', title: '状态', width: 76 }, const res = await listAdoptableUsers()
// 列总宽超出面板宽度时固定在右侧,避免"修改"按钮被横向滚动挤出可视区 adoptList.value = unwrap(res) || []
{ colKey: 'op', title: '操作', width: 84, fixed: 'right' }, adoptLoaded.value = true
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '加载可收编成员失败')
}
}
const onAdopt = async () => {
if (!adoptList.value.length) return
adopting.value = true
try {
const res = await adoptHomeTenant(adoptList.value.map((u) => u.id))
const result = unwrap(res)
const skipped = result?.skipped || []
MessagePlugin.success(`已收编 ${result?.adopted ?? 0} 名成员,自下次登录起默认进入本空间`)
// 预览与收编之间成员关系可能变化(被移出/停用),逐条原因只提示首条避免刷屏。
if (skipped.length) {
const first = skipped[0]
MessagePlugin.warning(
`${skipped.length} 名成员被跳过:如 ${first.username} ${first.reason}${skipped.length > 1 ? ' 等' : ''}`,
)
}
adoptVisible.value = false
loadEmployees()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '收编失败')
} finally {
adopting.value = false
}
}
const openRoles = (row: OrgEmployee) => {
activeEmployee.value = row
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
rolesVisible.value = true
}
const onSaveRoles = async () => {
if (!activeEmployee.value) return
savingRoles.value = true
try {
// 学员角色为全员隐式默认,保存时总是带回去(与后端口径一致)。
await updateOrgEmployeeRoles(activeEmployee.value.id, [...roleSelection.value, 'trainee'])
MessagePlugin.success('角色已更新')
rolesVisible.value = false
loadEmployees()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
savingRoles.value = false
}
}
const openWecom = (row: OrgEmployee) => {
activeWecomEmployee.value = row
wecomInput.value = row.wecom_userid || ''
wecomVisible.value = true
}
const onSaveWecom = async () => {
if (!activeWecomEmployee.value) return
savingWecom.value = true
try {
await updateOrgEmployeeWecomUserid(activeWecomEmployee.value.id, wecomInput.value.trim())
MessagePlugin.success('企微账号已更新')
wecomVisible.value = false
loadEmployees()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
savingWecom.value = false
}
}
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
const deptColumns = [
{ colKey: 'name', title: '部门名称' },
// 000164:编码列收窄(0001 等短编码无需过宽列,原 140px 留白明显)
{ colKey: 'code', title: '编码', width: 64 },
// 窄屏下列宽超出面板时操作列随滚动固定在右侧,保证可见可点
{ colKey: 'op', title: '操作', width: 116, fixed: 'right' },
] ]
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
const employeeColumns = computed(() => [
{ colKey: 'employee_no', title: '工号', width: 90 },
{ colKey: 'user_name', title: '姓名', width: 110 },
{ colKey: 'dept_name', title: '部门', width: 100 },
{ colKey: 'post', title: '岗位', width: 120 },
{ colKey: 'wecom_userid', title: '企微账号', width: 110 },
{ colKey: 'roles', title: '职称角色' },
{ colKey: 'status', title: '状态', width: 70 },
// 列总宽超出面板宽度时固定在右侧,避免操作按钮被横向滚动挤出可视区
{ colKey: 'op', title: '操作', width: canManage.value ? 200 : 84, fixed: 'right' },
])
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name, // 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。 // 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。
const userNameMap = computed(() => { const userNameMap = computed(() => {
@@ -249,23 +582,75 @@ watch(pickerUserIds, (ids) => {
if (deptId) pickerDeptId.value = deptId if (deptId) pickerDeptId.value = deptId
}) })
const loadAll = async () => { // 员工列表:module_key='training' 联查职称角色展示;keyword 按姓名/工号/部门过滤。
const loadEmployees = async () => {
loading.value = true loading.value = true
try { try {
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。 const e = await listEmployees({
const [d, e, u] = await Promise.all([ module_key: ORG_MODULE_TRAINING,
listDepts(), keyword: keyword.value.trim() || undefined,
listEmployees({ page_size: 500 }), page_size: 500,
listPlatformUsers().catch(() => null), })
])
depts.value = unwrap(d) || []
employees.value = unwrap(e)?.items || [] employees.value = unwrap(e)?.items || []
platformUsers.value = unwrap(u) || []
} finally { } finally {
loading.value = false loading.value = false
} }
} }
// 输入防抖触发查找(enter/clear 立即触发由模板回调完成)
let searchTimer: ReturnType<typeof setTimeout> | undefined
watch(keyword, () => {
clearTimeout(searchTimer)
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 () => {
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
const [d, u] = await Promise.all([
listDepts(),
listPlatformUsers().catch(() => null),
])
depts.value = unwrap(d) || []
platformUsers.value = unwrap(u) || []
await loadEmployees()
}
// 本人职称角色(人事/经理/空间管理员可维护;口径与培训页 canManageConfig 一致)
const loadProfile = async () => {
try {
const res = await getMyProfile() as any
const member: OrgEmployee | undefined = res?.data?.data || res?.data
if (member) {
rawRoles.value = (member.roles as unknown as string[]) || ['trainee']
}
} catch {
// 取不到档案按纯学员兜底:仅隐藏维护入口,不影响页面其余功能。
rawRoles.value = ['trainee']
}
}
const openCreateDept = () => { const openCreateDept = () => {
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' } deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
deptFormVisible.value = true deptFormVisible.value = true
@@ -349,7 +734,7 @@ const onPickImport = async () => {
pickerVisible.value = false pickerVisible.value = false
pickerUserIds.value = [] pickerUserIds.value = []
pickerDeptId.value = '' pickerDeptId.value = ''
loadAll() loadEmployees()
} catch { } catch {
MessagePlugin.error('添加失败') MessagePlugin.error('添加失败')
} finally { } finally {
@@ -385,7 +770,7 @@ const onSaveEmployee = async () => {
}) })
MessagePlugin.success('员工档案已更新') MessagePlugin.success('员工档案已更新')
employeeFormVisible.value = false employeeFormVisible.value = false
loadAll() loadEmployees()
} catch { } catch {
MessagePlugin.error('保存失败') MessagePlugin.error('保存失败')
} finally { } finally {
@@ -430,7 +815,7 @@ const onImport = async () => {
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`) MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
importVisible.value = false importVisible.value = false
importText.value = '' importText.value = ''
loadAll() loadEmployees()
} catch { } catch {
MessagePlugin.error('导入失败,请检查部门是否为已维护部门') MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
} finally { } finally {
@@ -438,7 +823,13 @@ const onImport = async () => {
} }
} }
onMounted(loadAll) onMounted(() => {
loadAll()
loadProfile()
fetchRoleDict().then((d) => {
roleDict.value = d
})
})
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@@ -462,16 +853,24 @@ onMounted(loadAll)
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 过宽且编码列留白明显),
// 员工档案占剩余全部宽度;窄屏退化为单列
.org-layout { .org-layout {
display: grid; display: grid;
grid-template-columns: 3fr 7fr; grid-template-columns: 280px minmax(0, 1fr);
gap: 12px; gap: 12px;
align-items: start; align-items: start;
@media (max-width: 900px) { @media (max-width: 900px) {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
// 000164 栅格子项收敛:员工档案表格/工具行较宽,缺省 min-width 会把
// 栅格轨道撑出视口,右侧列与操作按钮被裁掉不可见不可点;
// 收敛后表格在面板内横向滚动,操作列 fixed:right 始终可见
> .panel-box {
min-width: 0;
}
} }
.panel-box { .panel-box {
@@ -498,4 +897,55 @@ onMounted(loadAll)
word-break: break-all; word-break: break-all;
line-height: 1.4; line-height: 1.4;
} }
// 员工面板头部工具条:提示文案 + 查找框 + 动作按钮(窄屏折行)
.org-employees__actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
min-width: 0;
}
.org-employees__hint {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.org-employees__search {
width: 200px;
}
.oa-sync-btn {
white-space: nowrap;
}
.role-tag {
margin-right: 4px;
}
.wecom-missing {
color: var(--td-text-color-placeholder);
}
.sync-stats {
display: flex;
gap: 14px;
flex-wrap: wrap;
margin-bottom: 12px;
color: var(--td-text-color-secondary);
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
}
.sync-section {
margin-bottom: 12px;
max-height: 180px;
overflow: auto;
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
}
.sync-footer {
display: flex;
gap: 8px;
justify-content: flex-end;
}
// 收编弹窗说明文案
.adopt-hint {
margin: 0 0 10px;
}
</style> </style>
+408 -31
View File
@@ -1,19 +1,24 @@
<template> <template>
<!-- 学员扫码签到落地页:培训签到页二维码 → 企微/相机扫码直达,自动定位并提交签到 --> <!-- 学员扫码签到落地页(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-${state}`"> <div class="checkin-card__icon" :class="`is-${iconState}`">
<!-- 定位中/提交中 --> <!-- 加载中/取位中 -->
<svg v-if="state === '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" />
</svg> </svg>
<!-- 成功 --> <!-- 成功 -->
<svg v-else-if="state === 'success'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"> <svg v-else-if="iconState === 'success'" 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="9" /> <circle cx="12" cy="12" r="9" />
<path d="m8.5 12.2 2.4 2.4 4.8-4.9" /> <path d="m8.5 12.2 2.4 2.4 4.8-4.9" />
</svg> </svg>
<!-- 失败 --> <!-- 失败/受阻 -->
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"> <svg v-else 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="9" /> <circle cx="12" cy="12" r="9" />
<path d="M12 7.5V13" /> <path d="M12 7.5V13" />
@@ -28,42 +33,286 @@
{{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }} {{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }}
</t-tag> </t-tag>
<!-- 落地页主体:课程信息 + 工号输入/确认行 + 倒计时 + 签到按钮 -->
<template v-if="state === 'ready' && page">
<div class="course-box">
<div class="course-box__name">{{ page.course?.course_name || '培训课程' }}</div>
<div class="course-box__row" v-if="page.course?.lecturer_name">讲师:{{ page.course.lecturer_name }}</div>
<div class="course-box__row" v-if="page.course?.start_at">时间:{{ fmtBeijingTime(page.course.start_at) }}</div>
<div class="course-box__row" v-if="page.course?.location">地点:{{ page.course.location }}</div>
<div class="course-box__row" v-if="memberLabel">签到人:{{ memberLabel }}</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) -->
<div class="countdown" :class="{ 'is-danger': remainSec <= 60 }">
<template v-if="remainSec > 0">
签到码有效期剩余 <b>{{ fmtRemain(remainSec) }}</b>
</template>
<template v-else>二维码已更新,请重新扫码签到</template>
</div>
<t-button
class="checkin-card__sign-btn"
theme="primary"
size="large"
block
:disabled="signDisabled"
@click="sign"
>
{{ signButtonText }}
</t-button>
<div v-if="signDisabledReason" class="checkin-card__warn">{{ signDisabledReason }}</div>
</template>
<div class="checkin-card__actions"> <div class="checkin-card__actions">
<t-button v-if="state === 'error'" theme="primary" @click="submit">重新签到</t-button> <t-button v-if="state === 'error' && retryable" theme="primary" @click="sign">重新签到</t-button>
<t-button variant="outline" @click="goTraining">前往企业培训</t-button> <t-button v-if="state !== 'submitting'" variant="outline" @click="goTraining">前往企业培训</t-button>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' 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 { checkin, unwrap, type TrainingSignRecord } from '@/api/training' import { useAuthStore } from '@/stores/auth'
import { userInfoFromApi } from '@/api/auth'
import {
checkin,
unwrap,
wecomCheckinByEmployee,
wecomCheckinPage,
wecomCheckinPageAnon,
wecomCheckinSession,
type TrainingSignRecord,
type WecomCheckinByEmployeeData,
type WecomCheckinPageData,
} from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const authStore = useAuthStore()
type CheckinState = 'pending' | 'success' | 'error' type CheckinState = 'boot' | 'ready' | 'submitting' | 'success' | 'error' | 'blocked'
const state = ref<CheckinState>('pending') const state = ref<CheckinState>('boot')
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 iconState = computed(() => {
if (state.value === 'success') return 'success'
if (state.value === 'error' || state.value === 'blocked') return 'error'
return 'pending'
})
const title = computed(() => { const title = computed(() => {
if (state.value === 'pending') return '正在签到…' switch (state.value) {
if (state.value === 'success') return '签到完成' case 'boot':
return '签到失败' return '正在打开签到页…'
case 'ready':
return page.value?.already_signed ? '您已签到' : '培训签到'
case 'submitting':
return '正在签到…'
case 'success':
return '签到完成'
default:
return state.value === 'blocked' ? '无法签到' : '签到失败'
}
}) })
const hint = computed(() => { const hint = computed(() => {
if (state.value === 'pending') return '正在获取定位并提交签到,请保持页面打开' switch (state.value) {
if (state.value === 'success') return `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'}` case 'boot':
return errorMsg.value || '签到码无效或已过期,请联系讲师刷新签到码' return '正在加载课程签到信息,请稍候'
case 'ready':
if (page.value?.already_signed) return '本课程您已完成签到,无需重复操作'
return needEmployeeNo.value ? '请输入本人工号并点击签到' : '请核对签到人信息,点击下方按钮完成签到'
case 'submitting':
return '正在获取定位并提交签到,请保持页面打开'
case 'success':
return authStore.isLoggedIn
? `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'},即将进入课程详情…`
: `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'}`
case 'blocked':
return errorMsg.value || '签到码无效或已过期,请重新扫码'
default:
return errorMsg.value || '签到失败,请重试'
}
}) })
// 错误态是否提供「重新签到」:仅瞬时失败(定位/网络/工号笔误)可重试;
// 名单外/非当天/重复签到属确定性拒绝,提示后不重试。
const retryable = computed(() => {
const msg = errorMsg.value
return !(/名单|当天|已结束|尚未开始|重复扫码|已签到/.test(msg))
})
// ---- 落地页主体态(ready) ----
// 匿名主流程:落地页未带成员信息(工号未输入),需学员手输工号。
const needEmployeeNo = computed(() => !page.value?.member)
const memberLabel = computed(() => {
const m = page.value?.member
if (!m) return ''
return [m.user_name, m.employee_no].filter(Boolean).join(' · ')
})
const remainSec = ref(0)
let countdownTimer: number | undefined
const startCountdown = () => {
stopCountdown()
const tick = () => {
const exp = page.value?.sign_expire_at
remainSec.value = exp ? Math.max(0, Math.floor((new Date(exp).getTime() - Date.now()) / 1000)) : 0
}
tick()
countdownTimer = window.setInterval(tick, 1000)
}
const stopCountdown = () => {
if (countdownTimer) {
window.clearInterval(countdownTimer)
countdownTimer = undefined
}
}
const fmtRemain = (sec: number) => {
const m = Math.floor(sec / 60)
const s = sec % 60
return m > 0 ? `${m}分${String(s).padStart(2, '0')}秒` : `${s}秒`
}
const signDisabled = computed(() => {
if (!page.value) return true
if (page.value.already_signed) return true
if (remainSec.value <= 0) 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
})
const signDisabledReason = computed(() => {
if (!page.value) return ''
if (page.value.already_signed) return '本课程您已完成签到'
if (remainSec.value <= 0) return '签到码已过期,请重新扫码'
if (page.value.course && !page.value.course.can_sign_today) {
const start = page.value.course.start_at ? fmtBeijingTime(page.value.course.start_at) : ''
return `培训尚未开始(${start} 开课),培训当天再来签到`
}
if (page.value.member && !page.value.in_roster) return '您不在该课程的「参加人员」名单中,请联系讲师或人事确认'
return ''
})
const signButtonText = computed(() => {
if (page.value?.already_signed) return '已签到'
if (state.value === 'submitting') return '签到中…'
return needEmployeeNo.value ? '输入工号签到' : '点击签到'
})
// ---- 登录态持久化(与 /auth/login 同构,复用 Login.vue 持久化路径) ----
type LoginPayload = {
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 }>
}
const persistLogin = (data: LoginPayload) => {
const activeTenant = data.active_tenant || null
const homeTenantIdRaw = data.user?.tenant_id ?? activeTenant?.id ?? ''
if (data.user) authStore.setUser(userInfoFromApi(data.user, homeTenantIdRaw))
authStore.setToken(data.token || '')
if (data.refresh_token) authStore.setRefreshToken(data.refresh_token)
if (activeTenant) {
authStore.setTenant({
id: String(activeTenant.id) || '',
name: activeTenant.name || '',
owner_id: String(data.user?.id || ''),
created_at: activeTenant.created_at || new Date().toISOString(),
updated_at: activeTenant.updated_at || new Date().toISOString(),
})
} else {
authStore.setTenant(null)
}
if (Array.isArray(data.memberships)) authStore.setMemberships(data.memberships)
// 后端按"最近活跃租户"偏好落点时,同步选中态让后续请求带 X-Tenant-ID。
const activeIdNum = Number(activeTenant?.id)
const homeIdNum = Number(homeTenantIdRaw)
if (Number.isFinite(activeIdNum) && Number.isFinite(homeIdNum) && activeIdNum !== homeIdNum) {
authStore.setSelectedTenant(activeIdNum, activeTenant?.name || null)
} else {
authStore.setSelectedTenant(null, null)
}
}
// ---- 链路编排 ----
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) => {
try {
const data = unwrap<WecomCheckinByEmployeeData & LoginPayload>(await wecomCheckinSession(code, stateToken))
if (!data?.token) throw new Error('empty session token')
persistLogin(data)
applyPage(data)
// 清理回跳参数,避免刷新重复消费一次性 code。
window.history.replaceState(null, '', window.location.pathname)
} catch (e: any) {
state.value = 'blocked'
errorMsg.value = e?.response?.data?.message || '免登失败,请重新扫码'
}
}
// 已登录(PC 讲师自测/已有会话):取落地页数据并预填工号。
const loadPage = async () => {
try {
const data = unwrap<WecomCheckinPageData>(await wecomCheckinPage(routeToken.value))
if (!data) throw new Error('empty page data')
applyPage(data)
} catch (e: any) {
// 登录态失效等:回退匿名主流程(工号手输),不阻塞签到。
await loadAnonPage(e)
}
}
// 匿名主流程(扫码默认):未登录学员落地页,工号手输签到。
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'
errorMsg.value = e?.response?.data?.message || presetErr?.response?.data?.message || '签到码无效或已过期,请重新扫码'
}
}
// 取定位:最多等 6 秒,失败不阻塞签到(是否强制定位由后端规则决定) // 取定位:最多等 6 秒,失败不阻塞签到(是否强制定位由后端规则决定)
const locate = () => const locate = () =>
new Promise<void>((resolve) => { new Promise<void>((resolve) => {
@@ -77,29 +326,73 @@ const locate = () =>
}, },
() => { () => {
window.clearTimeout(timer) window.clearTimeout(timer)
MessagePlugin.warning('未获取到定位,如课程开启定位校验将无法签到') MessagePlugin.warning('未获取到定位,如课程开启定位校验将标记定位异常')
resolve() resolve()
}, },
{ timeout: 5500, maximumAge: 30000 }, { timeout: 5500, maximumAge: 30000 },
) )
}) })
const submit = async () => { // 点击签到(需求:进页不自动签):工号 + 随机时间戳随请求提交,后端按规则
state.value = 'pending' // 校验(当天/名单硬拒/围栏/迟到/重复/nonce 防重放)。
const token = String(route.params.token || '') const sign = async () => {
if (!token) { if (!page.value || signDisabled.value || state.value === 'submitting') return
state.value = 'error' const employeeNo = employeeNoInput.value.trim()
errorMsg.value = '签到链接不完整' if (needEmployeeNo.value && !employeeNo) {
MessagePlugin.warning('请先输入工号')
return return
} }
state.value = 'submitting'
errorMsg.value = ''
await locate() await locate()
const nonce = `${Date.now()}${Math.random().toString(36).slice(2, 10)}`
try { try {
const res = await checkin(token, geo.value.lat, geo.value.lng, 'wecom_scan') if (needEmployeeNo.value) {
record.value = (unwrap(res) as TrainingSignRecord | undefined) || null // 工号主流程:规则校验 + 工号反查档案 + 自动登录一次完成。
state.value = 'success' const data = unwrap<WecomCheckinByEmployeeData>(
await wecomCheckinByEmployee({
token: routeToken.value,
employee_no: employeeNo,
nonce,
lat: geo.value.lat,
lng: geo.value.lng,
client_ts: Date.now(),
}),
)
record.value = data?.record || null
// 回填成员/课程信息(展示签到人行);自动登录关闭(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'
}
} 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 || '签到码无效或已过期,请联系讲师刷新签到码' errorMsg.value = e?.response?.data?.message || '签到失败,请重试'
} }
} }
@@ -107,7 +400,28 @@ const goTraining = () => {
router.push('/platform/training/dashboard') router.push('/platform/training/dashboard')
} }
onMounted(submit) onMounted(() => {
const oauthCode = route.query.code ? String(route.query.code) : ''
const oauthState = route.query.state ? String(route.query.state) : ''
if (oauthCode && oauthState) {
// 预留通道:企微 OAuth 回跳(URL 带 code+state 时才消费,当前主流程不走)。
exchangeSession(oauthCode, oauthState)
return
}
if (!routeToken.value) {
state.value = 'blocked'
errorMsg.value = '签到链接不完整'
return
}
if (authStore.isLoggedIn) {
loadPage()
return
}
// 扫码默认:匿名主流程(课程信息 + 工号手输签到)。
loadAnonPage()
})
onBeforeUnmount(stopCountdown)
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@@ -115,8 +429,10 @@ onMounted(submit)
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 {
@@ -173,6 +489,16 @@ onMounted(submit)
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
&__sign-btn {
margin-top: 4px;
}
&__warn {
color: var(--td-warning-color, #e37318);
font-size: var(--app-text-sm, 13px);
overflow-wrap: anywhere;
}
&__actions { &__actions {
display: flex; display: flex;
gap: 10px; gap: 10px;
@@ -180,6 +506,57 @@ onMounted(submit)
} }
} }
.course-box {
width: 100%;
padding: 14px 16px;
margin-top: 4px;
text-align: left;
background: var(--td-bg-color-secondarycontainer, rgba(0, 0, 0, 0.03));
border-radius: var(--app-radius-md, 8px);
&__name {
margin-bottom: 6px;
font-weight: 600;
font-size: var(--app-text-lg, 16px);
}
&__row {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm, 13px);
line-height: 1.8;
overflow-wrap: anywhere;
}
}
.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 {
width: 100%;
padding: 8px 12px;
color: var(--td-success-color);
font-size: var(--app-text-sm, 13px);
background: var(--td-success-color-1, rgba(0, 168, 112, 0.08));
border-radius: var(--app-radius-md, 8px);
b {
font-weight: 600;
}
&.is-danger {
color: var(--td-error-color);
background: var(--td-error-color-1, rgba(227, 77, 89, 0.08));
}
}
@keyframes checkin-breath { @keyframes checkin-breath {
0%, 100% { opacity: 1; } 0%, 100% { opacity: 1; }
50% { opacity: 0.55; } 50% { opacity: 0.55; }
+55 -27
View File
@@ -13,6 +13,12 @@
</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 查询参数) -->
<t-button v-if="course" variant="outline" theme="primary" size="small" class="detail-signin" @click="goSignin">
培训签到
</t-button>
</div> </div>
<div class="detail-meta"> <div class="detail-meta">
<span v-if="course">学时 {{ course.hours }}<template v-if="course.credits"> · 学分 {{ course.credits }}</template></span> <span v-if="course">学时 {{ course.hours }}<template v-if="course.credits"> · 学分 {{ course.credits }}</template></span>
@@ -49,17 +55,15 @@
<!-- 预览区 --> <!-- 预览区 -->
<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">
<DocumentPreview <!-- 课程已下线(000163):不能再打开学习,统一提示 -->
v-if="current && docBlob" <t-empty
:source-blob="docBlob" v-if="libraryOffline"
:file-type="previewKind(current)" class="preview-empty"
:file-name="current.name" description="该课程已下线,不能再继续学习;如有疑问请联系培训管理员"
active
fill-height
/> />
<DocumentPreview <DocumentPreview
v-else-if="current && isDoc(current)" v-else-if="current && docBlob"
:knowledge-id="current.knowledge_id" :source-blob="docBlob"
:file-type="previewKind(current)" :file-type="previewKind(current)"
:file-name="current.name" :file-name="current.name"
active active
@@ -75,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">
@@ -186,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] || '' : ''
@@ -209,7 +217,6 @@ const previewKind = (m: TrainingMaterial) => {
return 'unsupported' return 'unsupported'
} }
const isVideo = (m: TrainingMaterial) => previewKind(m) === 'video' || (!m.knowledge_id && !!m.file_key) const isVideo = (m: TrainingMaterial) => previewKind(m) === 'video' || (!m.knowledge_id && !!m.file_key)
const isDoc = (m: TrainingMaterial) => !isVideo(m) && (m.knowledge_id || m.file_key)
const kindIcon = (m: TrainingMaterial) => { const kindIcon = (m: TrainingMaterial) => {
const kind = previewKind(m) const kind = previewKind(m)
@@ -225,28 +232,31 @@ const stopHeartbeat = () => {
docPercentStep = 0 docPercentStep = 0
} }
// 打开课件:文档带 knowledge_id 时走知识库流(DocumentPreview 自带拉取); // 打开课件:统一走培训域课件文件流(blob 播放/渲染)。不走知识库文档预览
// 视频/仅 file_key 的课件统一走课件文件流(blob 播放/渲染)。 // 通道(/knowledge/:id/preview):该通道按调用方所在空间做知识库鉴权,000160
// 跨空间学员(培训数据在档案空间)会被 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
docBlob.value = null docBlob.value = null
if (!m.knowledge_id && !m.file_key) return if (!m.knowledge_id && !m.file_key) return
if (isVideo(m) || !m.knowledge_id) { previewLoading.value = true
previewLoading.value = true try {
try { docBlob.value = await downloadMaterialFile(m.id)
docBlob.value = await downloadMaterialFile(m.id) if (isVideo(m)) bindVideoHeartbeat()
if (isVideo(m)) bindVideoHeartbeat() else startDocHeartbeat(m)
} catch { } catch {
MessagePlugin.error('课件文件加载失败,请稍后重试') MessagePlugin.error('课件文件加载失败,请稍后重试')
current.value = null current.value = null
} finally { } finally {
previewLoading.value = false previewLoading.value = false
}
return
} }
startDocHeartbeat(m)
} }
// ---- 学习进度心跳 ---- // ---- 学习进度心跳 ----
@@ -312,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))
@@ -358,6 +372,12 @@ const goBack = () => {
else router.push('/platform/training/dashboard') else router.push('/platform/training/dashboard')
} }
// 培训签到:携 courseId 跳「培训签到」页,SignPanel.applyRouteCourse 自动选中
// 该课程的进行中/最近场次(与「月培训计划-记录」跳转同一查询参数口径)。
const goSignin = () => {
router.push({ path: '/platform/training/sign', query: { courseId } })
}
const loadAll = async () => { const loadAll = async () => {
loading.value = true loading.value = true
try { try {
@@ -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 {
@@ -414,6 +436,12 @@ onMounted(loadAll)
flex-shrink: 0; flex-shrink: 0;
} }
// 培训签到入口:页头行右对齐(2026-11 需求)
.detail-signin {
margin-left: auto;
flex-shrink: 0;
}
.detail-name { .detail-name {
margin: 0; margin: 0;
font-size: var(--app-text-xl, 20px); font-size: var(--app-text-xl, 20px);
+15 -10
View File
@@ -60,11 +60,6 @@
<t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" /> <t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" />
</template> </template>
<StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" /> <StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" />
<template v-else-if="activeTab === 'members'">
<!-- 职称角色对经理开放(000159):与配置中心「角色权限」页签同口径 -->
<MemberPanel v-if="canManageConfig" />
<t-empty v-else class="training-empty" description="职称角色维护仅人事/经理可见" />
</template>
<template v-else-if="activeTab === 'rules'"> <template v-else-if="activeTab === 'rules'">
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 --> <!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
<RulePanel v-if="canManageConfig" /> <RulePanel v-if="canManageConfig" />
@@ -86,7 +81,6 @@ import PlanPanel from './components/PlanPanel.vue'
import CoursePanel from './components/CoursePanel.vue' import CoursePanel from './components/CoursePanel.vue'
import LibraryPanel from './components/LibraryPanel.vue' import LibraryPanel from './components/LibraryPanel.vue'
import SignPanel from './components/SignPanel.vue' import SignPanel from './components/SignPanel.vue'
import MemberPanel from './components/MemberPanel.vue'
import StudyPanel from './components/StudyPanel.vue' import StudyPanel from './components/StudyPanel.vue'
import RulePanel from './components/RulePanel.vue' import RulePanel from './components/RulePanel.vue'
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training' import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
@@ -102,7 +96,7 @@ const TRAINING_TABS_META: Record<string, { title: string; desc: string }> = {
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' }, library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' }, sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' }, study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
members: { title: '职称角色', desc: '名册来自「组织架构」,此处维护员工职称角色' }, // members(职称角色)已并入「组织架构」页维护,路由 /platform/training/members 重定向过去
rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' }, rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' },
} }
@@ -116,10 +110,12 @@ const authStore = useAuthStore()
// 职称角色字典(配置中心可配);myRoles = 实际分配角色按「权限分配」传递展开后的 // 职称角色字典(配置中心可配);myRoles = 实际分配角色按「权限分配」传递展开后的
// 权限并集 —— 各子页既有 canXxx 判断因此对自定义角色自动生效,无需逐一修改。 // 权限并集 —— 各子页既有 canXxx 判断因此对自定义角色自动生效,无需逐一修改。
const roleDict = ref<TrainingRoleDef[]>([]) const roleDict = ref<TrainingRoleDef[]>([])
const loadRoleDict = () =>
fetchRoleDict().then((d) => {
roleDict.value = d
})
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value)) const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
fetchRoleDict().then((d) => { loadRoleDict()
roleDict.value = d
})
// 空间 Admin/Owner 视同培训管理角色(与后端 requireRoles 的 bypass 一致), // 空间 Admin/Owner 视同培训管理角色(与后端 requireRoles 的 bypass 一致),
// 保证冷启动时管理员即可进入职称角色/配置中心子页完成首批授权。 // 保证冷启动时管理员即可进入职称角色/配置中心子页完成首批授权。
@@ -213,6 +209,15 @@ const loadProfile = async () => {
onMounted(() => { onMounted(() => {
loadProfile() loadProfile()
}) })
// 侧栏在企业培训各子页间切换时复用同一页面实例(不重挂载):本人职称角色可能刚在
// 「职称角色」子页被分配/回收,角色权限字典可能刚在「配置中心」子页被修改。切换
// 子页时重取这两项,否则各子页会沿用挂载时的旧 myRoles —— 例如刚给自己分配了
// 课长,课程管理的核验/删除按钮却不出现,须整页刷新才生效。
watch(activeTab, () => {
loadProfile()
loadRoleDict()
})
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@@ -30,12 +30,15 @@
<template v-if="filter === 'mine'"> <template v-if="filter === 'mine'">
<span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span> <span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span>
<span class="catalog-stats__pending" :class="{ 'is-info': pendingStartCount > 0 }">待开始 {{ pendingStartCount }} 门</span> <span class="catalog-stats__pending" :class="{ 'is-info': pendingStartCount > 0 }">待开始 {{ pendingStartCount }} 门</span>
<!-- 我主讲/我参加统计(2026-11 需求):与卡片角标同口径着色(主讲橙/参加蓝) -->
<span class="catalog-stats__teach" :class="{ 'is-teach': teachingCount > 0 }">我主讲 {{ teachingCount }} 门</span>
<span class="catalog-stats__attend" :class="{ 'is-attend': attendCount > 0 }">我参加 {{ attendCount }} 门</span>
</template> </template>
</div> </div>
<!-- 我的考试:与我相关的考试记录列表(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>
@@ -43,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>
@@ -50,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"
@@ -95,19 +99,68 @@
<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):和信课程卡片点开即学 —— 课件在线预览 + 下载 -->
<t-drawer
v-model:visible="learningVisible"
:header="learningCourse?.name || '课程学习'"
size="860px"
:footer="false"
>
<div v-if="learningCourse" class="course-learning">
<p class="course-learning__meta">
{{
[
learningCourse.owner_dept_name,
learningCourse.suitable_members,
learningCourse.lecturer_name,
learningCourse.hours ? `${learningCourse.hours} 学时` : '',
]
.filter(Boolean)
.join(' · ')
}}
</p>
<t-loading :loading="learningLoading" text="课件加载中...">
<DocumentPreview
v-if="learningBlob"
:source-blob="learningBlob"
:file-type="learningFileType"
:file-name="learningCourse.file_name || learningCourse.name"
:active="learningVisible"
fill-height
/>
<t-empty
v-else-if="!learningLoading"
class="catalog-empty"
:description="learningCourse.file_name ? '课件加载失败,可下载后本地查看' : '该课程未上传课件,请联系讲师或人事补充'"
/>
</t-loading>
<div v-if="learningCourse.file_name" class="course-learning__actions">
<t-button variant="outline" theme="primary" @click="onDownloadLearningMaterial">下载课件</t-button>
</div>
</div>
</t-drawer>
</div> </div>
</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 DocumentPreview from '@/components/document-preview.vue'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
import { import {
downloadCourseLibraryMaterial,
getMyProfile, getMyProfile,
listCourses, listCourses,
listCourseLibrary, listCourseLibrary,
listMyEnrolledCourseIds,
listMyExamRecords, listMyExamRecords,
listMyLearningTasks, listMyLearningTasks,
listSessions, listSessions,
@@ -125,9 +178,13 @@ const props = defineProps<{ roles: string[]; admin?: boolean }>()
const router = useRouter() const router = useRouter()
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试); // 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护; // 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护;
// 和信课程卡片为课程资产展示(000154),无学习页不跳转。 // 和信课程卡片点开即学(000160):打开课件在线预览抽屉。
const openCourse = (card: CatalogCard) => { const openCourse = (card: CatalogCard) => {
if (card.kind === 'library') return if (card.kind === 'library') {
const course = hexinCourses.value.find((c) => c.id === card.id)
if (course) openLibraryCourse(course)
return
}
if (card.unpublished) { if (card.unpublished) {
goMaintain(card.id) goMaintain(card.id)
return return
@@ -140,6 +197,52 @@ const goMaintain = (courseId: string) => {
router.push({ path: '/platform/training/course', query: { courseId } }) router.push({ path: '/platform/training/course', query: { courseId } })
} }
// ---- 和信课程学习抽屉(000160):点开卡片 → 课件在线预览 + 下载 ----
const learningVisible = ref(false)
const learningCourse = ref<TrainingLibraryCourse | null>(null)
const learningBlob = ref<Blob | null>(null)
const learningLoading = ref(false)
// 预览组件按扩展名分派渲染器(pptx/pdf/docx/图片/文本...)
const learningFileType = computed(() => {
const name = learningCourse.value?.file_name || ''
const dot = name.lastIndexOf('.')
return dot >= 0 ? name.slice(dot + 1).toLowerCase() : ''
})
const openLibraryCourse = (course: TrainingLibraryCourse) => {
learningCourse.value = course
learningBlob.value = null
learningVisible.value = true
if (!course.file_name) return
learningLoading.value = true
downloadCourseLibraryMaterial(course.id)
.then((blob) => {
learningBlob.value = blob
})
.catch(() => {
learningBlob.value = null
})
.finally(() => {
learningLoading.value = false
})
}
const onDownloadLearningMaterial = async () => {
const course = learningCourse.value
if (!course?.file_name) return
try {
const blob = await downloadCourseLibraryMaterial(course.id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = course.file_name || `${course.name}课件`
a.click()
URL.revokeObjectURL(url)
} catch {
MessagePlugin.error('课件下载失败')
}
}
const loading = ref(false) const loading = ref(false)
const courses = ref<TrainingCourse[]>([]) const courses = ref<TrainingCourse[]>([])
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计 // 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计
@@ -147,6 +250,8 @@ const lecturerCourses = ref<TrainingCourse[]>([])
const myProfile = ref<TrainingMember | null>(null) const myProfile = ref<TrainingMember | null>(null)
const myTasks = ref<LearningTask[]>([]) const myTasks = ref<LearningTask[]>([])
const sessions = ref<TrainingCourseSession[]>([]) const sessions = ref<TrainingCourseSession[]>([])
// 我经场次学员名单报名的课程 id 集合(「我参加」判定;失败回退空集不阻断)
const myEnrolledCourseIds = ref<Set<string>>(new Set())
// 课程管理资产(000154):「和信课程」目录 = 课程管理已发布且部门范围覆盖查看人的课程 // 课程管理资产(000154):「和信课程」目录 = 课程管理已发布且部门范围覆盖查看人的课程
const libraryItems = ref<TrainingLibraryCourse[]>([]) const libraryItems = ref<TrainingLibraryCourse[]>([])
// 我的考试记录(000154):「我的考试」页签数据源 // 我的考试记录(000154):「我的考试」页签数据源
@@ -160,17 +265,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'))
// 「和信课程」(000154):课程管理中已发布、且部门范围覆盖查看人的课程 // 「和信课程」(000160):已发布课程目录。课程权限(000163)由后端 scope=catalog
// (所属部门为空 = 全员课程;有部门则需与我的部门一致) // 按调用方部门/人员统一过滤,此处只保留发布状态过滤 —— 不再做客户端权限复算:
const myDeptId = computed(() => myProfile.value?.dept_id || '') // 此前按我的档案部门/用户 id 复算,调用方档案缺部门(或 id 口径不一致)时会把
// 服务端已授权的课程误杀,表现为「审核通过后和信课程看不到」(2026-11-26 复测修复)。
const hexinCourses = computed<TrainingLibraryCourse[]>(() => const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
libraryItems.value.filter( libraryItems.value.filter((c) => c.publish_status === 'published'),
(c) => c.publish_status === 'published' && (!c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value),
),
) )
const statsText = computed(() => { const statsText = computed(() => {
@@ -206,13 +320,16 @@ const myTaskByCourse = computed(() => {
// 「我的课程」相关性口径(与后端推送口径一致): // 「我的课程」相关性口径(与后端推送口径一致):
// ① 我有该课学习任务(线上必修按部门推送);② 我是该课讲师; // ① 我有该课学习任务(线上必修按部门推送);② 我是该课讲师;
// ③ 课程部门范围覆盖我(dept_ids 为空 = 全员可见,非空需包含我的部门)。 // ③ 课程部门范围覆盖我(dept_ids 为空 = 全员可见,非空需包含我的部门);
// ④ 我是该课场次参加人员(学员名单接口,线下课参加人员由此可见——此前参加
// 人员只落名单与文案,不进任何"与我相关"判定,被设为参加人员却看不到课)。
// 讲师匹配用平台用户 id(user_id)——与后端 course.LecturerID == callerUserID 同口径。 // 讲师匹配用平台用户 id(user_id)——与后端 course.LecturerID == callerUserID 同口径。
const myUserId = computed(() => myProfile.value?.user_id || '') const myUserId = computed(() => myProfile.value?.user_id || '')
const isMyTeaching = (c: TrainingCourse) => !!myUserId.value && c.lecturer_id === myUserId.value const isMyTeaching = (c: TrainingCourse) => !!myUserId.value && c.lecturer_id === myUserId.value
const isMyCourse = (c: TrainingCourse) => { const isMyCourse = (c: TrainingCourse) => {
if (myTaskByCourse.value.has(c.id)) return true if (myTaskByCourse.value.has(c.id)) return true
if (isMyTeaching(c)) return true if (isMyTeaching(c)) return true
if (myEnrolledCourseIds.value.has(c.id)) return true
const scope = c.dept_ids || [] const scope = c.dept_ids || []
if (!scope.length) return true if (!scope.length) return true
return !!myProfile.value && scope.includes(myProfile.value.dept_id) return !!myProfile.value && scope.includes(myProfile.value.dept_id)
@@ -243,6 +360,13 @@ const myCoursesSource = computed<TrainingCourse[]>(() => {
// 待维护 = 我主讲且「草稿」状态的课程(2026-11 需求:待审/已发布缺课件不再计入统计) // 待维护 = 我主讲且「草稿」状态的课程(2026-11 需求:待审/已发布缺课件不再计入统计)
const maintainCount = computed(() => myTeachingCourses.value.filter((c) => c.status === 'draft').length) const maintainCount = computed(() => myTeachingCourses.value.filter((c) => c.status === 'draft').length)
// 我主讲/我参加统计(2026-11 需求):我主讲含未发布(与「我的培训」页签同源);
// 我参加 = 我在名单中的已发布课程数(纯参加口径,主讲不计,与「我参加」角标一致)
const teachingCount = computed(() => myTeachingCourses.value.length)
const attendCount = computed(() =>
publishedCourses.value.filter((c) => myEnrolledCourseIds.value.has(c.id) && !isMyTeaching(c)).length,
)
// 置顶排序/维护按钮仍关注未发布(草稿/待审)或已发布但未上传课件的课程 // 置顶排序/维护按钮仍关注未发布(草稿/待审)或已发布但未上传课件的课程
const needsMaintain = (c: TrainingCourse) => c.status !== 'published' || !c.material_ids?.length const needsMaintain = (c: TrainingCourse) => c.status !== 'published' || !c.material_ids?.length
@@ -380,7 +504,9 @@ const visibleCards = computed<CatalogCard[]>(() => {
} }
return list return list
.map((c) => { .map((c) => {
const head = [c.post_scope, typeText(c), `${c.hours} 学时`, c.exam_enabled ? '随堂考试' : ''].filter(Boolean).join(' · ') // meta 首段为参加人员文案(post_scope),加「参加:」前缀——裸名字会被误读成讲师名
// (讲师身份以「我主讲」角标为准,角标判定口径见 isMyTeaching)。
const head = [c.post_scope ? `参加:${c.post_scope}` : '', typeText(c), `${c.hours} 学时`, c.exam_enabled ? '随堂考试' : ''].filter(Boolean).join(' · ')
const maintainable = isMyTeaching(c) && canMaintainCourses.value const maintainable = isMyTeaching(c) && canMaintainCourses.value
const unpublished = c.status !== 'published' const unpublished = c.status !== 'published'
// 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记 // 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记
@@ -435,23 +561,53 @@ 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 过滤),
// 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。 // 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
const needMaintainView = props.admin || props.roles.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r)) const needMaintainView = props.admin || props.roles.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r))
const [c, t, s, me, lc, lib, exams] = await Promise.all([ const [c, t, s, me, lc, lib, exams, enrolled] = await Promise.all([
// 学员目录视图:scope=student 统一走已发布课程口径(讲师账号的学习视角不受课程维护范围影响) // 学员目录视图:scope=student 统一走已发布课程口径(讲师账号的学习视角不受课程维护范围影响)
listCourses({ page_size: 100, scope: 'student' }), listCourses({ page_size: 100, scope: 'student' }),
listMyLearningTasks().catch(() => null), listMyLearningTasks().catch(() => null),
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),
// 和信课程目录(000154):课程管理已发布课程 // 和信课程目录(000160):scope=catalog —— 已发布 + 课程权限覆盖查看人
listCourseLibrary({ page_size: 500 }).catch(() => null), // (000163 部门/人员 id 精确匹配;存量课程沿用老口径),后端按权限过滤
listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => {
// 目录查询失败不再静默吞成「暂无课程」(此前服务版本与数据库迁移不一致
// 时表现为「审核通过后和信课程看不到」且无任何提示,2026-11-26 复测修复)
catalogLoadFailed.value = true
return null
}),
// 我的考试记录(000154) // 我的考试记录(000154)
listMyExamRecords().catch(() => null), listMyExamRecords().catch(() => null),
// 我经场次学员名单报名的课程 id(「我参加」判定;旧后端无此接口时回退空集)
listMyEnrolledCourseIds().catch(() => null),
]) ])
courses.value = unwrap(c)?.items || [] courses.value = unwrap(c)?.items || []
myTasks.value = (t && unwrap(t)) || [] myTasks.value = (t && unwrap(t)) || []
@@ -460,6 +616,7 @@ const loadAll = async () => {
lecturerCourses.value = (lc && unwrap(lc)?.items) || [] lecturerCourses.value = (lc && unwrap(lc)?.items) || []
libraryItems.value = (lib && unwrap(lib)?.items) || [] libraryItems.value = (lib && unwrap(lib)?.items) || []
myExamRecords.value = (exams && unwrap(exams)) || [] myExamRecords.value = (exams && unwrap(exams)) || []
myEnrolledCourseIds.value = new Set((enrolled && unwrap(enrolled)) || [])
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -556,6 +713,26 @@ onMounted(loadAll)
font-weight: 600; font-weight: 600;
} }
} }
// 我主讲统计:与「我主讲」角标同色(warning 橙)
&__teach {
margin-left: 6px;
&.is-teach {
color: var(--td-warning-color);
font-weight: 600;
}
}
// 我参加统计:与「我参加」角标同色(primary 蓝)
&__attend {
margin-left: 6px;
&.is-attend {
color: var(--td-brand-color);
font-weight: 600;
}
}
} }
.catalog-grid-wrap { .catalog-grid-wrap {
@@ -573,6 +750,26 @@ onMounted(loadAll)
padding: 48px 0; padding: 48px 0;
} }
// 课程学习抽屉(000160):元信息行 + 预览主体 + 下载操作
.course-learning {
display: flex;
flex-direction: column;
gap: 12px;
min-height: 100%;
&__meta {
margin: 0;
color: var(--td-text-color-secondary);
font-size: 13px;
}
&__actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
}
// 「我的考试」成绩列:及格绿/不及格红 // 「我的考试」成绩列:及格绿/不及格红
.exam-score { .exam-score {
font-weight: 600; font-weight: 600;
@@ -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 = ''
@@ -4,26 +4,31 @@
<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">
<t-button theme="primary" @click="openCreate('offline')">创建线下计划</t-button> <!-- 000163:线上线下经弹窗内「形式」切换,只保留一个创建入口 -->
<t-button variant="outline" @click="openCreate('online')">创建线上计划</t-button> <t-button theme="primary" @click="openCreate('offline')">创建月度计划</t-button>
</div> </div>
</div> </div>
<!-- 查询条件:名称/讲师/培训时间范围/状态。计划列表全量加载(page_size=100), <!-- 查询条件:名称/讲师/培训月份/状态。计划列表全量加载(page_size=100),
企业内部数据量小,过滤在前端本地完成,不新增后端查询参数。 --> 企业内部数据量小,过滤在前端本地完成,不新增后端查询参数。
000163:默认只看当月(计划培训/授课时间任一命中),月份可多选,清空=全部数据。 -->
<div class="course-filters"> <div class="course-filters">
<t-input v-model="filters.keyword" placeholder="按计划名称查询" clearable style="width: 200px" /> <t-input v-model="filters.keyword" placeholder="按计划名称查询" clearable style="width: 200px" />
<t-select v-if="!isLecturerOnly" v-model="filters.lecturerId" placeholder="按讲师查询" clearable style="width: 150px"> <t-select v-if="!isLecturerOnly" v-model="filters.lecturerId" placeholder="按讲师查询" clearable style="width: 150px">
<t-option v-for="l in lecturers" :key="l.id" :value="l.id" :label="l.name" /> <t-option v-for="l in lecturers" :key="l.id" :value="l.id" :label="l.name" />
</t-select> </t-select>
<t-date-range-picker <t-select
v-model="filters.teachRange" v-model="filters.months"
format="YYYY-MM-DD" multiple
separator="至"
clearable clearable
:placeholder="['按开始日期', '按结束日期']" filterable
style="width: 260px" collapse-tags
/> :min-collapsed-num="2"
placeholder="按培训月份筛选(可多选,清空为全部)"
style="width: 280px"
>
<t-option v-for="m in monthOptions" :key="m" :value="m" :label="monthLabel(m)" />
</t-select>
<t-select v-model="filters.status" placeholder="按状态查询" clearable style="width: 130px"> <t-select v-model="filters.status" placeholder="按状态查询" clearable style="width: 130px">
<t-option v-for="opt in STATUS_OPTIONS" :key="opt.value" :value="opt.value" :label="opt.label" /> <t-option v-for="opt in STATUS_OPTIONS" :key="opt.value" :value="opt.value" :label="opt.label" />
</t-select> </t-select>
@@ -31,10 +36,13 @@
<span class="course-filter-count">共 {{ filteredCourses.length }} 门</span> <span class="course-filter-count">共 {{ filteredCourses.length }} 门</span>
</div> </div>
<t-table :data="filteredCourses" :columns="courseColumns" row-key="id" size="small" :loading="loading"> <t-table :data="pagedCourses" :columns="courseColumns" row-key="id" size="small" :loading="loading">
<template #plan_code="{ row }">{{ row.plan_code || '-' }}</template> <template #plan_code="{ row }">{{ row.plan_code || '-' }}</template>
<template #name="{ row }"> <template #name="{ row }">
<span class="course-name-link clamp-2" title="点击前往培训签到" @click="goSignTab(row)">{{ row.name }}</span> <span class="course-name-link clamp-2" title="点击前往培训签到" @click="goSignTab(row)">{{ row.name }}</span>
<!-- 课程已下线(000163):关联课程管理条目 offline 时标注(计划行保留,
学习入口提示「该课程已下线」) -->
<t-tag v-if="row.library_offline" theme="danger" variant="outline" size="small" class="offline-flag">课程已下线</t-tag>
</template> </template>
<template #mode="{ row }"> <template #mode="{ row }">
<t-tag :theme="row.mode === 'online' ? 'primary' : 'default'" variant="light" size="small" :class="{ 'course-tag-offline': row.mode !== 'online' }"> <t-tag :theme="row.mode === 'online' ? 'primary' : 'default'" variant="light" size="small" :class="{ 'course-tag-offline': row.mode !== 'online' }">
@@ -71,15 +79,17 @@
variant="text" theme="primary" size="small" :disabled="saving" variant="text" theme="primary" size="small" :disabled="saving"
@click="onPublish(row)" @click="onPublish(row)"
>发布</t-button> >发布</t-button>
<t-button variant="text" size="small" @click="openDetail(row)">详情</t-button> <t-button variant="text" size="small" @click="openDetail(row)">调整</t-button>
<t-button variant="text" size="small" @click="openChangeLogs(row)">记录</t-button> <t-button variant="text" size="small" @click="openChangeLogs(row)">记录</t-button>
<t-button v-if="canManage" variant="text" theme="danger" size="small" @click="onDelete(row)">删除</t-button> <t-button v-if="canManage" variant="text" theme="danger" size="small" @click="onDelete(row)">删除</t-button>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="coursePage" v-model:page-size="coursePageSize" :total="courseTotal" />
</div> </div>
<!-- 创建计划:课程名称从课程管理选择(带出并锁定课程信息),仅维护授课安排六字段 --> <!-- 创建计划:课程名称从课程管理选择(带出并锁定课程信息),仅维护授课安排六字段 -->
<t-dialog v-model:visible="formVisible" :header="form.mode === 'online' ? '创建线上计划' : '创建线下计划'" width="720"> <t-dialog v-model:visible="formVisible" header="创建月度计划" width="720">
<t-form label-width="100"> <t-form label-width="100">
<t-form-item label="计划编号"> <t-form-item label="计划编号">
<t-input value="保存后自动生成" disabled /> <t-input value="保存后自动生成" disabled />
@@ -98,6 +108,14 @@
</t-select> </t-select>
<div class="bank-hint">选择后带出课程信息且不可修改,仅可调整下方授课安排;还没有课程?<a class="template-link" href="javascript:void(0)" @click.prevent="goLibrary">前往「课程管理」新增</a></div> <div class="bank-hint">选择后带出课程信息且不可修改,仅可调整下方授课安排;还没有课程?<a class="template-link" href="javascript:void(0)" @click.prevent="goLibrary">前往「课程管理」新增</a></div>
</t-form-item> </t-form-item>
<t-form-item label="形式">
<!-- 计划「形式」独立字段(000162):指本次培训线上办还是线下办,与课程
主数据的线上课/线下课口径不同,不随所选课程带出,可在此切换 -->
<t-radio-group v-model="form.mode" variant="default-filled" size="small">
<t-radio-button value="offline">线下(集中授课)</t-radio-button>
<t-radio-button value="online">线上(自主学习)</t-radio-button>
</t-radio-group>
</t-form-item>
<t-form-item label="类型"> <t-form-item label="类型">
<t-input :value="formTypeDisplay" disabled /> <t-input :value="formTypeDisplay" disabled />
</t-form-item> </t-form-item>
@@ -107,15 +125,91 @@
<t-form-item label="所属部门"> <t-form-item label="所属部门">
<t-input :value="deptNamesOf(form.dept_ids)" disabled placeholder="随课程带出" /> <t-input :value="deptNamesOf(form.dept_ids)" disabled placeholder="随课程带出" />
</t-form-item> </t-form-item>
<!-- 课程资产侧信息随所选课程带出(000156):只读展示;维护入口见详情弹窗「更换」或课程管理 --> <!-- 课程资产侧信息随所选课程带出(000156);000163 起课件/试题可在创建时
上传/更换(回写课程管理主数据,变更后课程回「待审核」须课长/经理审核) -->
<t-form-item label="适合人员"> <t-form-item label="适合人员">
<t-input :value="formLibraryCourse?.suitable_members || '-'" disabled placeholder="随所选课程带出" /> <t-input :value="formLibraryCourse?.suitable_members || '-'" disabled placeholder="随所选课程带出" />
</t-form-item> </t-form-item>
<t-form-item label="课件"> <t-form-item label="课件">
<t-input :value="formLibraryCourse?.material_name || formLibraryCourse?.file_name || '-'" disabled placeholder="随所选课程带出" /> <div class="asset-row">
<t-input
:value="formLibraryCourse?.material_name || formLibraryCourse?.file_name || '-'"
disabled
placeholder="随所选课程带出,可上传/更换"
class="asset-value"
/>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="formMaterialInput?.click()"
>上传课件</t-button>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="openFormKbCourseware"
>知识库</t-button>
<input ref="formMaterialInput" type="file" class="hidden-file-input" @change="onFormChangeMaterial" />
</div>
<div v-if="formKbCoursewareVisible" class="asset-relink">
<t-select
v-model="formKbCoursewareDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(课件)」知识库文档作为课件"
style="flex: 1"
>
<t-option v-for="doc in kbCoursewareDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formKbCoursewareDocId" @click="onFormAttachKbCourseware">确定</t-button>
</div>
<div class="bank-hint">课件上传/更换后自动回写课程管理,该课程回「待审核」,需所属部门课长/经理审核后方可发布计划</div>
</t-form-item> </t-form-item>
<t-form-item label="试题"> <t-form-item label="试题">
<t-input :value="formCourseBanksText" disabled placeholder="随所选课程带出" /> <div class="asset-row">
<t-input
:value="formCourseBanksText"
disabled
placeholder="随所选课程带出,可更换"
class="asset-value"
/>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="formRelinkVisible = !formRelinkVisible"
>更换试题</t-button>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="openFormKbBank"
>知识库</t-button>
</div>
<div v-if="formRelinkVisible" class="asset-relink">
<t-select
v-model="formRelinkBankId"
filterable
clearable
placeholder="选择题库替换该课程当前试题"
style="flex: 1"
>
<t-option
v-for="b in allBanks"
:key="b.id"
:value="b.id"
:label="`${b.name}(${b.question_count}题)`"
/>
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formRelinkBankId" @click="onFormRelinkBank">确认更换</t-button>
</div>
<div v-if="formKbBankVisible" class="asset-relink">
<t-select
v-model="formKbBankDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(题库)」知识库文档解析建题库"
style="flex: 1"
>
<t-option v-for="doc in kbBankDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formKbBankDocId" @click="onFormImportKbBank">确定</t-button>
</div>
</t-form-item> </t-form-item>
<t-form-item label="学时 / 学分"> <t-form-item label="学时 / 学分">
<t-input-number v-model="form.hours" :min="0" :step="0.5" :disabled="!form.library_course_id" style="width: 48%" /> <t-input-number v-model="form.hours" :min="0" :step="0.5" :disabled="!form.library_course_id" style="width: 48%" />
@@ -188,23 +282,24 @@
</div> </div>
</t-form-item> </t-form-item>
</t-form> </t-form>
<div class="form-hint">发布后将自动生成计划与学员名单(线下计划含签到码),并推送讲师与学员通知;适合人员/课件/试题随所选课程自动带出,详情弹窗可更换(自动同步课程管理),选择课程时自动带出。</div> <div class="form-hint">发布后将自动生成计划与学员名单(线下计划含签到码),并推送讲师与学员通知;课程信息随所选课程带出,课件/试题可在本弹窗上传/更换(自动同步课程管理,变更后该课程回「待审核」,需课长/经理重新审核后方可发布)。</div>
<template #footer> <template #footer>
<t-button variant="outline" @click="formVisible = false">暂存草稿</t-button> <t-button variant="outline" :loading="saving" @click="onSaveDraft">暂存草稿</t-button>
<t-button theme="primary" :loading="saving" @click="onSave">保存并发布</t-button> <t-button theme="primary" :loading="saving" @click="onSave">保存并发布</t-button>
</template> </template>
</t-dialog> </t-dialog>
<!-- 计划详情:计划编号展示 + 课程名称(课程管理选择,信息锁定) + 六项授课安排维护 --> <!-- 计划调整:计划编号展示 + 课程名称/讲师(000161 可调整,讲师改动回写课程管理并重置待审核) + 六项授课安排维护 -->
<t-dialog v-model:visible="sessionsVisible" :header="`计划详情 · ${activeCourse?.name || ''}`" width="760" :footer="false"> <t-dialog v-model:visible="sessionsVisible" :header="`计划调整 · ${activeCourse?.name || ''}`" width="760" :footer="false">
<t-form label-width="90" class="detail-form"> <t-form label-width="90" class="detail-form">
<t-form-item label="计划编号"> <t-form-item label="计划编号">
<t-input :value="activeCourse?.plan_code || '-'" disabled /> <t-input :value="activeCourse?.plan_code || '-'" disabled />
</t-form-item> </t-form-item>
<t-form-item label="课程名称"> <t-form-item label="课程名称">
<!-- 未关联课程管理的计划可选定课程(选定后信息锁定);已关联直接锁定展示 --> <!-- 000161 可切换关联课程:改选即换 library_course_id,名称/类型随新课程带出
(形式为计划侧独立字段,000162 起不随课程联动);讲师改动保存后回写
课程管理并重置待审核,发布前须重新审核 -->
<t-select <t-select
v-if="!activeCourse?.library_course_id"
v-model="editForm.library_course_id" v-model="editForm.library_course_id"
:disabled="!canManage" :disabled="!canManage"
clearable clearable
@@ -215,13 +310,30 @@
> >
<t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" /> <t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" />
</t-select> </t-select>
<t-input v-else :value="editForm.name" disabled /> </t-form-item>
<t-form-item label="形式">
<!-- 计划「形式」独立字段(000162):可改线下/线上,不随所选课程带出 -->
<t-radio-group v-model="editForm.mode" variant="default-filled" size="small" :disabled="!canManage">
<t-radio-button value="offline">线下(集中授课)</t-radio-button>
<t-radio-button value="online">线上(自主学习)</t-radio-button>
</t-radio-group>
</t-form-item> </t-form-item>
<t-form-item label="类型"> <t-form-item label="类型">
<t-input :value="formTypeDisplay" disabled /> <t-input :value="formTypeDisplay" disabled />
</t-form-item> </t-form-item>
<t-form-item label="讲师"> <t-form-item label="讲师">
<t-input :value="lecturerDisplay(editForm.lecturer_id)" disabled placeholder="随课程带出" /> <!-- 000161 计划侧可改讲师:名册选择或直接输入外部讲师姓名 -->
<t-select
v-model="editForm.lecturer_id"
:disabled="!canManage"
clearable
filterable
creatable
placeholder="从讲师名册选择或直接输入外部讲师姓名"
style="width: 100%"
>
<t-option v-for="l in lecturers" :key="l.id" :label="l.name" :value="l.id" />
</t-select>
</t-form-item> </t-form-item>
<t-form-item label="所属部门"> <t-form-item label="所属部门">
<t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" /> <t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" />
@@ -412,7 +524,7 @@
<!-- 计划修改记录:每次保存的版本与字段级变更明细 --> <!-- 计划修改记录:每次保存的版本与字段级变更明细 -->
<t-dialog v-model:visible="changeLogsVisible" :header="`计划修改记录 · ${changeLogCourse?.name || ''}`" width="640" :footer="false"> <t-dialog v-model:visible="changeLogsVisible" :header="`计划修改记录 · ${changeLogCourse?.name || ''}`" width="640" :footer="false">
<t-table :data="changeLogs" :columns="changeLogColumns" row-key="id" size="small" :loading="changeLogsLoading"> <t-table :data="pagedChangeLogs" :columns="changeLogColumns" row-key="id" size="small" :loading="changeLogsLoading">
<template #changes="{ row }"> <template #changes="{ row }">
<div v-for="(c, idx) in row.changes || []" :key="idx" class="change-line"> <div v-for="(c, idx) in row.changes || []" :key="idx" class="change-line">
{{ c.label }}:{{ c.old || '—' }} → {{ c.new || '—' }} {{ c.label }}:{{ c.old || '—' }} → {{ c.new || '—' }}
@@ -421,6 +533,7 @@
<template #operator="{ row }">{{ operatorName(row.operator_id) }}</template> <template #operator="{ row }">{{ operatorName(row.operator_id) }}</template>
<template #created_at="{ row }">{{ fmtTime(row.created_at) }}</template> <template #created_at="{ row }">{{ fmtTime(row.created_at) }}</template>
</t-table> </t-table>
<TrainingPagination v-model:current="changeLogPage" v-model:page-size="changeLogPageSize" :total="changeLogTotal" />
<t-empty v-if="!changeLogsLoading && !changeLogs.length" description="暂无修改记录;计划信息每次保存后自动留痕" /> <t-empty v-if="!changeLogsLoading && !changeLogs.length" description="暂无修改记录;计划信息每次保存后自动留痕" />
</t-dialog> </t-dialog>
</div> </div>
@@ -465,6 +578,8 @@ import {
} from '@/api/training' } from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime' import { fmtBeijingTime } from '@/utils/datetime'
import { apiErrorMessage, get } from '@/utils/request' import { apiErrorMessage, get } from '@/utils/request'
import TrainingPagination from './TrainingPagination.vue'
import { plannedMonthSortKey, useTrainingPager } from './useTrainingPager'
const props = defineProps<{ roles: string[]; admin?: boolean }>() const props = defineProps<{ roles: string[]; admin?: boolean }>()
// 课程维护:人事/课长/讲师(roles 已按权限组展开,经理经课长继承自动命中); // 课程维护:人事/课长/讲师(roles 已按权限组展开,经理经课长继承自动命中);
@@ -751,6 +866,136 @@ const formVisible = ref(false)
const sessionsVisible = ref(false) const sessionsVisible = ref(false)
const activeCourse = ref<TrainingCourse | null>(null) const activeCourse = ref<TrainingCourse | null>(null)
// ---- 创建弹窗课件/试题维护(000163):与调整弹窗同口径,直接回写课程管理
// 主数据;课件/试题变更后端自动置该课程「待审核」,须课长/经理审核后方可发布 ----
const formAssetSaving = ref(false)
const formMaterialInput = ref<HTMLInputElement | null>(null)
const formKbCoursewareVisible = ref(false)
const formKbCoursewareDocId = ref('')
const formRelinkVisible = ref(false)
const formRelinkBankId = ref('')
const formKbBankVisible = ref(false)
const formKbBankDocId = ref('')
// 创建弹窗目标课程条目:未选课程时按钮已禁用,这里兜底提示
const requireFormLibraryCourse = (): TrainingLibraryCourse | null => {
const lc = formLibraryCourse.value
if (!lc) MessagePlugin.warning('请先从课程管理选择课程')
return lc || null
}
const openFormKbCourseware = async () => {
formKbCoursewareVisible.value = !formKbCoursewareVisible.value
formKbBankVisible.value = false
if (!formKbCoursewareVisible.value) return
await ensureKbRefs()
await loadKbDocs('courseware')
}
const openFormKbBank = async () => {
formKbBankVisible.value = !formKbBankVisible.value
formKbCoursewareVisible.value = false
if (!formKbBankVisible.value) return
await ensureKbRefs()
await loadKbDocs('question_bank')
}
// 上传课件:文件直接回写课程管理条目(名称登记为空时后端以文件名兜底)
const onFormChangeMaterial = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
const lc = requireFormLibraryCourse()
if (!lc || !file) return
formAssetSaving.value = true
try {
const fd = new FormData()
fd.append('file', file)
const updated = unwrap(await uploadCourseLibraryMaterial(lc.id, fd)) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
MessagePlugin.success(`课件已上传到课程「${lc.name}」课件列表(追加不替换),该课程回「待审核」,需所属部门课长/经理审核后方可发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件上传失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 从知识库选文档挂为课件(与上传同口径,变更后回「待审核」)
const onFormAttachKbCourseware = async () => {
const lc = requireFormLibraryCourse()
const doc = kbCoursewareDocs.value.find((d) => d.id === formKbCoursewareDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库课件文档')
return
}
formAssetSaving.value = true
try {
const updated = unwrap(await attachCourseLibraryMaterialFromKb(lc.id, { knowledge_id: doc.id })) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
MessagePlugin.success(`课件「${doc.file_name}」已挂接为课程「${lc.name}」最新课件(原课件保留),课程回「待审核」,需课长/经理审核后方可发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 更换试题:所选题库整体替换该课程条目的题库(后端同步重置审核状态)
const onFormRelinkBank = async () => {
const lc = requireFormLibraryCourse()
if (!lc || !formRelinkBankId.value) {
if (lc && !formRelinkBankId.value) MessagePlugin.warning('请先选择要挂接的题库')
return
}
formAssetSaving.value = true
try {
const banks = (unwrap(await linkLibraryCourseQuestionBank(lc.id, formRelinkBankId.value)) || []) as TrainingQuestionBank[]
// 同步本地题库总表的挂接关系(与调整弹窗 onRelinkBank 同口径)
const linked = new Set(banks.map((b) => b.id))
allBanks.value = allBanks.value.map((b) => {
if (b.library_course_id === lc.id) return { ...b, library_course_id: linked.has(b.id) ? b.id : '' }
if (b.id === formRelinkBankId.value) return { ...b, library_course_id: lc.id }
return b
})
formRelinkVisible.value = false
formRelinkBankId.value = ''
MessagePlugin.success(`试题已更换到课程「${lc.name}」,该课程回「待审核」,需课长/经理审核后方可发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 从知识库题库文档解析建题库并挂当前所选课程条目(后端同步重置审核状态)
const onFormImportKbBank = async () => {
const lc = requireFormLibraryCourse()
const doc = kbBankDocs.value.find((d) => d.id === formKbBankDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库题库文档')
return
}
formAssetSaving.value = true
try {
const bank = unwrap(await importQuestionBankFromKnowledge({
knowledge_id: doc.id,
name: doc.file_name.replace(/\.[^.]+$/, ''),
library_course_id: lc.id,
})) as TrainingQuestionBank | null
formKbBankVisible.value = false
formKbBankDocId.value = ''
if (bank) allBanks.value = [bank, ...allBanks.value.filter((b) => b.id !== bank.id)]
MessagePlugin.success(`试题已更换为知识库题库「${bank?.name || doc.file_name}」,课程「${lc.name}」回「待审核」,需课长/经理审核后方可发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 讲师只读展示:员工名册映射姓名,外部讲师直接显示 // 讲师只读展示:员工名册映射姓名,外部讲师直接显示
const lecturerDisplay = (lecturerId: string) => { const lecturerDisplay = (lecturerId: string) => {
if (lecturerId) { if (lecturerId) {
@@ -832,6 +1077,7 @@ const openChangeLogs = async (row: TrainingCourse) => {
changeLogCourse.value = row changeLogCourse.value = row
changeLogsVisible.value = true changeLogsVisible.value = true
changeLogsLoading.value = true changeLogsLoading.value = true
resetChangeLogPage()
try { try {
const res = await listCourseChangeLogs(row.id) const res = await listCourseChangeLogs(row.id)
changeLogs.value = unwrap(res) || [] changeLogs.value = unwrap(res) || []
@@ -863,17 +1109,24 @@ const form = ref({
description: '', description: '',
}) })
// 从课程管理选择课程:带出课程信息(类型/形式/讲师/学时/所属部门/说明)并锁定, // 从课程管理选择课程:带出课程信息(名称/类型/讲师/学时/所属部门/说明)并锁定,
// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员) // 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员);
// 「形式」为计划侧独立字段(000162),不随所选课程带出,由表单自行选择
const onLibraryCourseChange = (libraryCourseId: unknown) => { const onLibraryCourseChange = (libraryCourseId: unknown) => {
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId) const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
form.value.name = lc?.name || '' form.value.name = lc?.name || ''
form.value.mode = lc?.mode === 'online' ? 'online' : 'offline'
form.value.type = lc?.type === 'elective' ? 'elective' : 'required' form.value.type = lc?.type === 'elective' ? 'elective' : 'required'
form.value.hours = lc?.hours || form.value.hours form.value.hours = lc?.hours || form.value.hours
form.value.lecturer_id = lc?.lecturer_id || '' form.value.lecturer_id = lc?.lecturer_id || ''
form.value.description = lc?.description || '' form.value.description = lc?.description || ''
form.value.dept_ids = lc?.owner_dept_id ? [lc.owner_dept_id] : [] form.value.dept_ids = lc?.owner_dept_id ? [lc.owner_dept_id] : []
// 换选课程后重置课件/试题维护的临时选择状态(000163)
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
formRelinkVisible.value = false
formRelinkBankId.value = ''
formKbBankVisible.value = false
formKbBankDocId.value = ''
} }
// 「前往课程管理」:切到课程管理子页(同页内由 Training 按路由 tab 切换面板) // 「前往课程管理」:切到课程管理子页(同页内由 Training 按路由 tab 切换面板)
@@ -948,7 +1201,7 @@ const courseColumns = [
{ colKey: 'op', title: '操作', width: 180, fixed: 'right' }, { colKey: 'op', title: '操作', width: 180, fixed: 'right' },
] ]
// ---- 查询条件(名称/讲师/培训时间/状态;列表全量加载,本地过滤) ---- // ---- 查询条件(名称/讲师/培训月份/状态;列表全量加载,本地过滤) ----
const STATUS_OPTIONS = [ const STATUS_OPTIONS = [
{ value: 'draft', label: '草稿' }, { value: 'draft', label: '草稿' },
{ value: 'pending', label: '待审' }, { value: 'pending', label: '待审' },
@@ -956,17 +1209,50 @@ const STATUS_OPTIONS = [
{ value: 'archived', label: '已归档' }, { value: 'archived', label: '已归档' },
] ]
// 当月(YYYY-MM,000163):默认只展示计划培训/授课时间任一命中当月的计划
const now = new Date()
const currentMonthKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
const filters = ref({ const filters = ref({
keyword: '', keyword: '',
lecturerId: '' as string | '', lecturerId: '' as string | '',
status: '', status: '',
teachRange: [] as string[], // 培训月份多选(000163):默认当月;清空 = 全部数据
months: [currentMonthKey] as string[],
}) })
const resetFilters = () => { const resetFilters = () => {
filters.value = { keyword: '', lecturerId: '', status: '', teachRange: [] } filters.value = { keyword: '', lecturerId: '', status: '', months: [currentMonthKey] }
resetCoursePage()
} }
// 月份归一:「YYYY-M」/「YYYY-MM-DD HH:mm」等统一取 YYYY-MM;无法解析返回空
const monthKeyOf = (value: string | null | undefined): string => {
const m = (value || '').trim().match(/^(\d{4})-(\d{1,2})/)
return m ? `${m[1]}-${String(Number(m[2])).padStart(2, '0')}` : ''
}
// 月份下拉展示:2026-11 → 2026年11月
const monthLabel = (key: string) => {
const m = key.match(/^(\d{4})-(\d{2})$/)
return m ? `${m[1]}年${Number(m[2])}月` : key
}
// 计划的培训月份集合(000163):计划培训时间 + 授课时间(含最近场次回退)任一命中即算
const courseMonthKeys = (row: TrainingCourse): string[] => {
const keys = [monthKeyOf(row.planned_time), monthKeyOf(row.teach_time), monthKeyOf(teachDateValue(row))]
return [...new Set(keys.filter(Boolean))]
}
// 月份筛选选项:当月 + 计划数据中实际出现的月份,倒序展示
const monthOptions = computed(() => {
const set = new Set<string>([currentMonthKey])
for (const row of courses.value) {
for (const k of courseMonthKeys(row)) set.add(k)
}
return [...set].sort().reverse()
})
// 授课时间过滤口径与列展示一致:teach_time(具体时间/期望月份)优先,否则最近场次开始时间, // 授课时间过滤口径与列展示一致:teach_time(具体时间/期望月份)优先,否则最近场次开始时间,
// 统一归一为 YYYY-MM-DD 后做字符串范围比较。 // 统一归一为 YYYY-MM-DD 后做字符串范围比较。
const teachDateValue = (row: TrainingCourse): string | null => { const teachDateValue = (row: TrainingCourse): string | null => {
@@ -982,25 +1268,51 @@ const teachDateValue = (row: TrainingCourse): string | null => {
return shown ? shown.replaceAll('/', '-').slice(0, 10) : null return shown ? shown.replaceAll('/', '-').slice(0, 10) : null
} }
// 计划培训时间排序键:计划培训时间优先,缺失时回退授课时间(含最近场次)
const courseSortKey = (row: TrainingCourse): number => {
const pk = plannedMonthSortKey(row.planned_time)
if (pk >= 0) return pk
return plannedMonthSortKey(row.teach_time || teachDateValue(row))
}
const filteredCourses = computed(() => { const filteredCourses = computed(() => {
const kw = filters.value.keyword.trim().toLowerCase() const kw = filters.value.keyword.trim().toLowerCase()
const range = filters.value.teachRange || [] const months = filters.value.months || []
const from = range[0] ? String(range[0]).slice(0, 10) : '' const list = courses.value.filter((row) => {
const to = range[1] ? String(range[1]).slice(0, 10) : ''
return courses.value.filter((row) => {
if (kw && !(row.name || '').toLowerCase().includes(kw)) return false if (kw && !(row.name || '').toLowerCase().includes(kw)) return false
if (filters.value.lecturerId && row.lecturer_id !== filters.value.lecturerId) return false if (filters.value.lecturerId && row.lecturer_id !== filters.value.lecturerId) return false
if (filters.value.status && row.status !== filters.value.status) return false if (filters.value.status && row.status !== filters.value.status) return false
if (from || to) { // 000163 月份筛选:计划培训时间/授课时间任一命中所选月份即可;清空 = 全部数据。
const v = teachDateValue(row) // 未填计划/授课时间的计划(如暂存草稿)无月份可命中,始终展示,
if (!v) return false // 避免默认当月视图下刚暂存的草稿“看不见”
if (from && v < from) return false if (months.length) {
if (to && v > to) return false const keys = courseMonthKeys(row)
if (keys.length && !months.some((m) => keys.includes(m))) return false
} }
return true return true
}) })
// 000163:按计划培训时间倒序(缺失计划培训时间的行按授课时间,均无则排最后)
return list.slice().sort((a, b) => courseSortKey(b) - courseSortKey(a))
}) })
// 共用分页(000163):计划列表默认每页 15 条
const {
page: coursePage,
pageSize: coursePageSize,
total: courseTotal,
paged: pagedCourses,
reset: resetCoursePage,
} = useTrainingPager(filteredCourses)
// 计划修改记录弹窗分页(000163)
const {
page: changeLogPage,
pageSize: changeLogPageSize,
total: changeLogTotal,
paged: pagedChangeLogs,
reset: resetChangeLogPage,
} = useTrainingPager(changeLogs)
const statusText = (s: string) => ({ draft: '草稿', pending: '待审', published: '已发布', archived: '已归档' }[s] || s) const statusText = (s: string) => ({ draft: '草稿', pending: '待审', published: '已发布', archived: '已归档' }[s] || s)
const statusTheme = (s: string) => ({ draft: 'default', pending: 'warning', published: 'success', archived: 'default' }[s] || 'default') const statusTheme = (s: string) => ({ draft: 'default', pending: 'warning', published: 'success', archived: 'default' }[s] || 'default')
const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '待定' const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '待定'
@@ -1033,6 +1345,16 @@ const courseLocation = (row: TrainingCourse) => {
// 回退课程自身地点(来自需求确认同步落库的 course.location) // 回退课程自身地点(来自需求确认同步落库的 course.location)
return nearest?.location || row.location || '' return nearest?.location || row.location || ''
} }
// 最靠前的有效场次(带授课时间或地点):发布前置校验与列表展示同口径用
// (课程级授课时间/地点为空的存量草稿,场次已排期即视为已维护,2026-11-26)
const firstUsableSession = (row: TrainingCourse) => {
const list = courseSessions.value[row.id] || []
return (
list.find((s) => s.status === 'scheduled' && (s.start_at || s.location)) ||
list.find((s) => s.start_at || s.location) ||
null
)
}
// 授课时间展示:期望月份默认值(YYYY-MM)→「2026/11」;具体时间 → 北京时间无秒;线上课默认「长期」 // 授课时间展示:期望月份默认值(YYYY-MM)→「2026/11」;具体时间 → 北京时间无秒;线上课默认「长期」
const teachTimeText = (row: TrainingCourse) => { const teachTimeText = (row: TrainingCourse) => {
if (row.mode === 'online') return row.teach_time ? teachTimeDisplay(row.teach_time) : '长期' if (row.mode === 'online') return row.teach_time ? teachTimeDisplay(row.teach_time) : '长期'
@@ -1055,7 +1377,9 @@ const loadAll = async () => {
listMembers({ page_size: 500 }), listMembers({ page_size: 500 }),
listLecturers().catch(() => []), listLecturers().catch(() => []),
listSessions({ year: 0, month: 0 }).catch(() => []), listSessions({ year: 0, month: 0 }).catch(() => []),
listCourseLibrary({ page_size: 500 }).catch(() => null), // scope=plan(000163):创建月度计划选课口径 —— 维护角色可选全部部门课程,
// 不再按本部门收窄(后端对纯学员/无维护角色调用方仍按原范围收窄)
listCourseLibrary({ page_size: 500, scope: 'plan' }).catch(() => null),
listQuestionBanks({ page_size: 200 }).catch(() => null), listQuestionBanks({ page_size: 200 }).catch(() => null),
]) ])
courses.value = unwrap(c)?.items || [] courses.value = unwrap(c)?.items || []
@@ -1077,38 +1401,84 @@ const openCreate = (mode: 'offline' | 'online') => {
description: '', description: '',
} }
resetFormParticipants() resetFormParticipants()
// 重置课件/试题维护临时状态(000163),避免上一次打开的残留选择
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
formRelinkVisible.value = false
formRelinkBankId.value = ''
formKbBankVisible.value = false
formKbBankDocId.value = ''
formVisible.value = true formVisible.value = true
} }
// 创建计划保存载荷(000163 抽取复用):「保存并发布」与「暂存草稿」共用;
// 参加人员随载荷落 post_scope,发布后由场次名单同步
const buildSavePayload = () => ({
name: form.value.name,
mode: form.value.mode,
type: form.value.type,
hours: form.value.hours,
credits: form.value.credits,
dept_ids: form.value.dept_ids,
lecturer_id: form.value.lecturer_id || undefined,
teach_time: teachTimeOf(form.value),
// 000163 根因修复:授课地点须随课程落库(此前只写到场次,发布校验读
// course.location 恒为空,导致「已填授课地点仍提示需先设置授课地点」)
location: form.value.mode === 'offline' ? form.value.location.trim() : '',
// 000163:计划培训时间默认取授课时间所在月份(YYYY-MM)
planned_time: form.value.start_at ? form.value.start_at.slice(0, 7) : '',
post_scope: resolvedFormMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
// 课程管理关联(服务端据此带出并锁定课程信息,自动生成计划编号)
library_course_id: form.value.library_course_id,
description: form.value.description,
})
const onSave = async () => { const onSave = async () => {
if (!form.value.library_course_id || !form.value.name) { if (!form.value.library_course_id || !form.value.name) {
MessagePlugin.warning('请从课程管理选择课程(课程名称必选)') MessagePlugin.warning('请从课程管理选择课程(课程名称必选)')
return return
} }
// 000163 根因修复:此前「保存并发布」直接调发布接口,后端校验不过时前端只
// 报笼统的「保存失败」且不刷新列表(草稿其实已落库),表现为“无法创建月度计划”。
// 现与后端 PublishCourse 同口径,在提交前逐项拦截并给出明确提示。
const selectedLib = libraryCourses.value.find((c) => c.id === form.value.library_course_id)
// 000163:课程须已审核(审核通过即自动发布);未审核时发布被后端拦截,这里提前提示
if (selectedLib && selectedLib.verify_status !== 'confirmed') {
MessagePlugin.warning(
`课程「${selectedLib.name}」尚未审核,请先联系所属部门课长/经理在「课程管理」中审核(审核通过即发布)后再创建发布`,
)
return
}
// 讲师随课程管理锁定:线下计划缺讲师时提示先在课程管理维护 // 讲师随课程管理锁定:线下计划缺讲师时提示先在课程管理维护
if (form.value.mode === 'offline' && !form.value.lecturer_id) { if (form.value.mode === 'offline' && !form.value.lecturer_id) {
MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师后再创建线下计划') MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师后再创建线下计划')
return return
} }
// 线下计划另需授课时间/授课地点(后端发布校验同口径)
if (form.value.mode === 'offline') {
if (!form.value.start_at) {
MessagePlugin.warning('线下计划请先设置授课时间')
return
}
if (!form.value.location.trim()) {
MessagePlugin.warning('线下计划请先设置授课地点')
return
}
}
// 线上计划须已登记课件(名称登记/文件/知识库文档任一,随课程管理带出)
if (form.value.mode === 'online' && !(selectedLib?.material_name || selectedLib?.file_name || selectedLib?.knowledge_id)) {
MessagePlugin.warning('线上计划发布前需先在「课程管理」为该课程登记课件资料(上传课件/从知识库选择)')
return
}
// 参加人员必填(后端发布校验:post_scope 与场次名单任一非空)
const selectedMembers = resolvedFormMembers.value
if (!selectedMembers.length) {
MessagePlugin.warning('请先选择参加人员(推送与应培人员以「参加人员」名单为准)')
return
}
saving.value = true saving.value = true
try { try {
// 参加人员(与详情弹窗同构):选中员工写 post_scope,落库后同步为场次学员名单 const res = await saveCourse(buildSavePayload())
const selectedMembers = resolvedFormMembers.value
const postScope = selectedMembers.map((m) => m.user_name || m.employee_no).join('、')
const res = await saveCourse({
name: form.value.name,
mode: form.value.mode,
type: form.value.type,
hours: form.value.hours,
credits: form.value.credits,
dept_ids: form.value.dept_ids,
lecturer_id: form.value.lecturer_id || undefined,
teach_time: teachTimeOf(form.value),
post_scope: postScope,
// 课程管理关联(服务端据此带出并锁定课程信息,自动生成计划编号)
library_course_id: form.value.library_course_id,
description: form.value.description,
})
const course = unwrap(res) const course = unwrap(res)
if (!course) throw new Error('save failed') if (!course) throw new Error('save failed')
@@ -1142,7 +1512,19 @@ const onSave = async () => {
const session = rosterSession || await ensureCourseSession(course.id, sessionOpts) const session = rosterSession || await ensureCourseSession(course.id, sessionOpts)
if (session) await setEnrollments(session.id, selectedMembers.map((m) => m.id)) if (session) await setEnrollments(session.id, selectedMembers.map((m) => m.id))
} }
await publishCourse(course.id) // 000163 根因修复:发布与保存拆开处理 —— 发布校验不过时草稿已落库,
// 透出真实原因并刷新列表,草稿可在列表「调整」完善后再点「发布」。
try {
await publishCourse(course.id)
} catch (e: any) {
MessagePlugin.warning(
`计划已保存为草稿(计划编号 ${course.plan_code || '自动生成'}),发布失败:${apiErrorMessage(e, '请完善计划信息后再发布')};可在列表「调整」完善后点击「发布」`,
)
formVisible.value = false
resetFormParticipants()
loadAll()
return
}
MessagePlugin.success( MessagePlugin.success(
course.plan_code course.plan_code
? `计划 ${course.plan_code} 已保存并发布,讲师与学员通知已生成` ? `计划 ${course.plan_code} 已保存并发布,讲师与学员通知已生成`
@@ -1151,27 +1533,80 @@ const onSave = async () => {
formVisible.value = false formVisible.value = false
resetFormParticipants() resetFormParticipants()
loadAll() loadAll()
} catch { } catch (e: any) {
MessagePlugin.error('保存失败,请稍后重试') MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
} finally {
saving.value = false
}
}
// 暂存草稿(000163):此前按钮只关闭弹窗未落库,填写内容全部丢失;现按草稿
// 状态保存计划(不建场次/名单、不发布),可稍后在列表「调整」完善后「发布」。
// 草稿只要求选到课程,其余授课安排可留空待补。
const onSaveDraft = async () => {
if (!form.value.library_course_id || !form.value.name) {
MessagePlugin.warning('请从课程管理选择课程(课程名称必选)')
return
}
saving.value = true
try {
const res = await saveCourse(buildSavePayload())
const course = unwrap(res)
if (!course) throw new Error('save failed')
MessagePlugin.success(
course.plan_code
? `计划 ${course.plan_code} 已暂存为草稿,可在列表「调整」完善后点击「发布」`
: '计划已暂存为草稿,可在列表「调整」完善后点击「发布」',
)
formVisible.value = false
resetFormParticipants()
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '暂存失败,请稍后重试'))
} finally { } finally {
saving.value = false saving.value = false
} }
} }
const onPublish = async (row: TrainingCourse) => { const onPublish = async (row: TrainingCourse) => {
// 与后端同口径的前置校验:线上必须有课件,线下必须有讲师 // 与后端同口径的前置校验(000161):线上必须有课件;线下须有讲师(外部姓名
// 亦可)/授课时间/授课地点;两者均须已设置参加人员且关联课程已审核
if (row.mode === 'online') { if (row.mode === 'online') {
try { try {
const res = await listMaterials(row.id) const res = await listMaterials(row.id)
if (!(unwrap(res) || []).length) { if (!(unwrap(res) || []).length) {
MessagePlugin.warning(`「${row.name}」是线上计划,发布前需先登记课件资料`) // 计划未自带课件时回退课程管理课件(名称登记/文件/知识库文档,
return // 000156 随所选课程带出,详情弹窗「更换」也回写主数据)与后端同口径
const lc = libraryCourses.value.find((c) => c.id === (row.library_course_id || ''))
const hasLibCourseware = !!(lc?.material_name || lc?.file_name || lc?.knowledge_id)
if (!hasLibCourseware) {
MessagePlugin.warning(`「${row.name}」是线上计划,发布前需先登记课件资料`)
return
}
} }
} catch { } catch {
/* 查询失败时交由后端校验兜底 */ /* 查询失败时交由后端校验兜底 */
} }
} else if (!row.lecturer_id) { } else {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「详情」中指定讲师`) if (!row.lecturer_id && !row.lecturer_external) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中指定讲师`)
return
}
// 授课时间/地点与列表展示同口径(场次排期优先,课程级字段兜底):存量草稿
// 课程级字段为空但场次已排期时不再误报「未设置」(2026-11-26 复测修复,
// 后端 PublishCourse 同口径兜底)
const session = firstUsableSession(row)
if (!row.teach_time && !session?.start_at) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课时间`)
return
}
if (!courseLocation(row)) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课地点`)
return
}
}
if (!row.post_scope) {
MessagePlugin.warning(`「${row.name}」发布前需先在「调整」中设置参加人员`)
return return
} }
try { try {
@@ -1263,12 +1698,11 @@ const openDetail = async (row: TrainingCourse) => {
} }
} }
// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定, // 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定(形式除外,
// 适用部门变化经 watcher 自动同步参加人员名单 // 000162 计划形式独立可改),适用部门变化经 watcher 自动同步参加人员名单
const onDetailLibraryCourseChange = (libraryCourseId: unknown) => { const onDetailLibraryCourseChange = (libraryCourseId: unknown) => {
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId) const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
editForm.value.name = lc?.name || '' editForm.value.name = lc?.name || ''
editForm.value.mode = lc?.mode === 'online' ? 'online' : 'offline'
editForm.value.type = lc?.type === 'elective' ? 'elective' : 'required' editForm.value.type = lc?.type === 'elective' ? 'elective' : 'required'
editForm.value.hours = lc?.hours || editForm.value.hours editForm.value.hours = lc?.hours || editForm.value.hours
editForm.value.lecturer_id = lc?.lecturer_id || '' editForm.value.lecturer_id = lc?.lecturer_id || ''
@@ -1339,42 +1773,59 @@ const ensureCourseSession = async (
// 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。 // 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。
// 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须 // 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须
// 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。 // 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。
const detailSavePayload = (row: TrainingCourse) => ({ // 000161 讲师解析:名册 id 直接用;非名册值(creatable 直接输入)按外部讲师姓名落库
id: row.id, const resolveDetailLecturer = (row: TrainingCourse) => {
code: row.code, const v = (editForm.value.lecturer_id || '').trim()
name: editForm.value.name, if (!v) return { lecturerId: '', external: row.lecturer_external || '' }
mode: editForm.value.mode, if (lecturers.value.some((l) => l.id === v)) return { lecturerId: v, external: '' }
type: editForm.value.type, return { lecturerId: '', external: v }
hours: editForm.value.hours, }
credits: editForm.value.credits,
exam_enabled: row.exam_enabled, const detailSavePayload = (row: TrainingCourse) => {
dept_ids: editForm.value.dept_ids, const lecturer = resolveDetailLecturer(row)
lecturer_id: editForm.value.lecturer_id || undefined, return ({
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单 id: row.id,
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'), code: row.code,
description: row.description, name: editForm.value.name,
material_ids: row.material_ids, mode: editForm.value.mode,
tags: row.tags, type: editForm.value.type,
status: row.status, hours: editForm.value.hours,
teach_time: teachTimeOf(editForm.value), credits: editForm.value.credits,
planned_time: row.planned_time || '', exam_enabled: row.exam_enabled,
// 其余需求确认同步字段原样透传(详情表单不编辑,防止保存时被零值覆盖丢失) dept_ids: editForm.value.dept_ids,
train_type: row.train_type || '', lecturer_id: lecturer.lecturerId || undefined,
plant: row.plant || '', // 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
location: row.location || '', post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
session_count: row.session_count || 0, description: row.description,
lecturer_external: row.lecturer_external || '', material_ids: row.material_ids,
remark: row.remark || '', tags: row.tags,
// 课程管理关联(未关联的存量计划可在此选定课程;关联后服务端锁定带出字段) status: row.status,
library_course_id: editForm.value.library_course_id || row.library_course_id || '', teach_time: teachTimeOf(editForm.value),
}) planned_time: row.planned_time || '',
// 其余需求确认同步字段原样透传(详情表单不编辑,防止保存时被零值覆盖丢失)
train_type: row.train_type || '',
plant: row.plant || '',
// 000163:授课地点随课程落库(发布校验读 course.location;此前只写场次,
// 「调整」里改了授课地点发布仍提示未设置)
location: editForm.value.mode === 'offline'
? (editForm.value.location.trim() || row.location || '')
: (row.location || ''),
session_count: row.session_count || 0,
// 000161 讲师计划侧可改:名册 id 或外部讲师姓名
lecturer_external: lecturer.external,
remark: row.remark || '',
// 课程管理关联(000161 可切换;切换后类型/形式随新课程带出)
library_course_id: editForm.value.library_course_id || row.library_course_id || '',
})
}
const onSaveDetail = async () => { const onSaveDetail = async () => {
const row = activeCourse.value const row = activeCourse.value
if (!row) return if (!row) return
// 讲师随课程管理锁定:缺失时提示去课程管理维护(发布时后端也会强制校验) // 线下计划须指定讲师(名册 id 或外部姓名;发布时后端也会强制校验)
if (row.mode === 'offline' && !editForm.value.lecturer_id) { const lecturer = resolveDetailLecturer(row)
MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师') if (editForm.value.mode === 'offline' && !lecturer.lecturerId && !lecturer.external) {
MessagePlugin.warning('线下计划需先指定讲师(从名册选择或输入外部讲师姓名)')
return return
} }
detailSaving.value = true detailSaving.value = true
@@ -1388,7 +1839,7 @@ const onSaveDetail = async () => {
await saveCourse(detailSavePayload(row)) await saveCourse(detailSavePayload(row))
const sessionOpts = { const sessionOpts = {
mode: editForm.value.mode, mode: editForm.value.mode,
lecturerId: editForm.value.lecturer_id || undefined, lecturerId: lecturer.lecturerId || undefined,
startAt: editForm.value.start_at, startAt: editForm.value.start_at,
location: editForm.value.location, location: editForm.value.location,
hours: editForm.value.hours, hours: editForm.value.hours,
@@ -1402,7 +1853,7 @@ const onSaveDetail = async () => {
end_at: editForm.value.start_at ? new Date(new Date(editForm.value.start_at).getTime() + editForm.value.hours * 3600 * 1000).toISOString() : '', end_at: editForm.value.start_at ? new Date(new Date(editForm.value.start_at).getTime() + editForm.value.hours * 3600 * 1000).toISOString() : '',
location: editForm.value.location, location: editForm.value.location,
capacity: existing?.capacity ?? 0, capacity: existing?.capacity ?? 0,
lecturer_id: editForm.value.lecturer_id || undefined, lecturer_id: lecturer.lecturerId || undefined,
// [2026-11 推学员] 编辑排课时同步通知方式 // [2026-11 推学员] 编辑排课时同步通知方式
notify_mode: editForm.value.notify_mode, notify_mode: editForm.value.notify_mode,
}) })
@@ -1426,8 +1877,8 @@ const onSaveDetail = async () => {
) )
sessionsVisible.value = false sessionsVisible.value = false
loadAll() loadAll()
} catch { } catch (e: any) {
MessagePlugin.error('保存失败,请稍后重试') MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
} finally { } finally {
detailSaving.value = false detailSaving.value = false
} }
@@ -1458,6 +1909,11 @@ watch(() => route?.query?.courseId, openDetailFromRoute)
.training-panel-box(); .training-panel-box();
} }
// 表单项内提示文案(bank-hint/form-hint)统一另起一行展示在控件下方
.course-panel {
.training-form-hints-below();
}
.form-hint { .form-hint {
margin-top: 8px; margin-top: 8px;
color: var(--td-text-color-placeholder); color: var(--td-text-color-placeholder);
@@ -1711,6 +2167,11 @@ watch(() => route?.query?.courseId, openDetailFromRoute)
} }
} }
// 课程已下线标签(000163):紧跟课程名称,警示已下线课程不可再学习
.offline-flag {
margin-left: 6px;
}
.course-panel :deep(.t-table .t-table__cell) { .course-panel :deep(.t-table .t-table__cell) {
vertical-align: middle; vertical-align: middle;
} }
@@ -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
@@ -1,323 +0,0 @@
<template>
<div class="member-panel">
<!-- 员工档案(名册来自组织架构)+ 职称角色 -->
<div class="panel-box member-layout__members">
<div class="panel-box__header">
<span class="panel-box__title">员工档案</span>
<div class="member-panel__hint">
员工与部门在「<a class="member-panel__link" @click="goOrgCenter">组织架构</a>」中统一维护,此处仅配置职称角色
<t-button variant="outline" theme="primary" size="small" :loading="syncing" class="oa-sync-btn" @click="onPreviewSync">
从OA同步企微账号
</t-button>
</div>
</div>
<t-table :data="members" :columns="memberColumns" row-key="id" size="small" :loading="loading">
<template #user_name="{ row }">
<t-tooltip :content="memberName(row)" :disabled="!memberName(row)">
<span class="member-name">{{ memberName(row) || '-' }}</span>
</t-tooltip>
</template>
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
<template #wecom_userid="{ row }">
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
</template>
<template #roles="{ row }">
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
<t-button variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
</template>
</t-table>
</div>
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
<template #footer>
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
</template>
</t-dialog>
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
<template v-if="syncSummary">
<div class="sync-stats">
<span>本地员工 {{ syncSummary.local_candidates }}</span>
<span>OA 命中 {{ syncSummary.local_matched }}</span>
<span>已一致 {{ syncSummary.already_bound }}</span>
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
</div>
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
{{ cf.employee_no }} {{ cf.user_name || '' }}:
{{ conflictText(cf) }}
</div>
</div>
<div v-if="syncSummary.would_update" class="sync-section">
<div class="sync-section__title">将写入(最多展示 20 条)</div>
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
</div>
</div>
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
无需更新:绑定已一致或 OA 无匹配数据。
</div>
<div class="sync-footer">
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
theme="primary" :loading="syncing" @click="onApplySync">
确认写入
</t-button>
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
</div>
</template>
</t-dialog>
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
<t-select v-model="roleSelection" multiple style="width: 100%">
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
</t-select>
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onSaveRoles">保存</t-button>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import {
fetchRoleDict,
listMembers,
listPlatformUsers,
roleLabelOf,
updateMemberRoles,
updateMemberWecomUserid,
applyWecomUseridSync,
previewWecomUseridSync,
type PlatformUser,
type TrainingMember,
type TrainingRoleDef,
type WecomSyncConflict,
type WecomSyncSummary,
unwrap,
} from '@/api/training'
const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const members = ref<TrainingMember[]>([])
const platformUsers = ref<PlatformUser[]>([])
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
const roleDict = ref<TrainingRoleDef[]>([])
const rolesVisible = ref(false)
const activeMember = ref<TrainingMember | null>(null)
const roleSelection = ref<string[]>([])
// 企微账号绑定(培训提醒推送目标)
const wecomVisible = ref(false)
const activeWecomMember = ref<TrainingMember | null>(null)
const wecomInput = ref('')
const savingWecom = ref(false)
// OA 同步(工号 → 企微 userid,预览→写入两段式)
const syncVisible = ref(false)
const syncing = ref(false)
const syncSummary = ref<WecomSyncSummary | null>(null)
const conflictText = (cf: WecomSyncConflict) => {
switch (cf.reason) {
case 'duplicate_workcode_in_oa':
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
case 'bound_to_different_userid':
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
case 'userid_occupied':
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
default:
return cf.reason
}
}
const onPreviewSync = async () => {
syncing.value = true
try {
const res = await previewWecomUseridSync()
syncSummary.value = unwrap(res) ?? null
syncVisible.value = true
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
} finally {
syncing.value = false
}
}
const onApplySync = async () => {
syncing.value = true
try {
const res = await applyWecomUseridSync()
const summary = unwrap(res)
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
syncVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '写入失败')
} finally {
syncing.value = false
}
}
const memberColumns = [
{ colKey: 'employee_no', title: '工号', width: 100 },
{ colKey: 'user_name', title: '姓名' },
{ colKey: 'dept_name', title: '部门', width: 110 },
{ colKey: 'post', title: '岗位', width: 140 },
{ colKey: 'wecom_userid', title: '企微账号', width: 120 },
{ colKey: 'roles', title: '职称角色', width: 260 },
{ colKey: 'op', title: '操作', width: 170 },
]
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
// 跳转组织架构页(部门/员工档案的唯一维护入口)
const goOrgCenter = () => router.push('/platform/org-center')
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不再回退展示用户ID。
const userNameMap = computed(() => {
const m: Record<string, string> = {}
for (const u of platformUsers.value) m[u.id] = u.display_name?.trim() || u.username
return m
})
const memberName = (row: TrainingMember) => row.user_name || userNameMap.value[row.user_id] || ''
const loadAll = async () => {
loading.value = true
try {
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
const [m, u] = await Promise.all([
listMembers({ page_size: 500 }),
listPlatformUsers().catch(() => null),
])
members.value = unwrap(m)?.items || []
platformUsers.value = unwrap(u) || []
} finally {
loading.value = false
}
}
const openRoles = (row: TrainingMember) => {
activeMember.value = row
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
rolesVisible.value = true
}
const openWecom = (row: TrainingMember) => {
activeWecomMember.value = row
wecomInput.value = row.wecom_userid || ''
wecomVisible.value = true
}
const onSaveWecom = async () => {
if (!activeWecomMember.value) return
savingWecom.value = true
try {
await updateMemberWecomUserid(activeWecomMember.value.id, wecomInput.value.trim())
MessagePlugin.success('企微账号已更新')
wecomVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
savingWecom.value = false
}
}
const onSaveRoles = async () => {
if (!activeMember.value) return
saving.value = true
try {
await updateMemberRoles(activeMember.value.id, [...roleSelection.value, 'trainee'])
MessagePlugin.success('角色已更新')
rolesVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
saving.value = false
}
}
onMounted(() => {
loadAll()
fetchRoleDict().then((d) => {
roleDict.value = d
})
})
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.panel-box {
.training-panel-box();
}
.member-panel__hint {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.member-panel__link {
color: var(--td-brand-color);
cursor: pointer;
}
.role-tag { margin-right: 4px; }
.wecom-missing { color: var(--td-text-color-placeholder); }
.oa-sync-btn { margin-left: 12px; }
.sync-stats {
display: flex;
gap: 14px;
flex-wrap: wrap;
margin-bottom: 12px;
color: var(--td-text-color-secondary);
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
}
.sync-section {
margin-bottom: 12px;
max-height: 180px;
overflow: auto;
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
}
.sync-footer { display: flex; gap: 8px; justify-content: flex-end; }
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 姓名列:最多展示 2 行,超出省略(悬停 tooltip 看全名)
.member-name {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
word-break: break-all;
line-height: 1.4;
}
</style>
@@ -36,9 +36,9 @@
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" theme="danger" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchDelete">批量删除</t-button>
@@ -46,7 +46,7 @@
</div> </div>
<t-table <t-table
v-model:selected-row-keys="selectedDemandKeys" v-model:selected-row-keys="selectedDemandKeys"
:data="demands" :data="pagedDemands"
:columns="demandColumns" :columns="demandColumns"
row-key="id" row-key="id"
size="small" size="small"
@@ -99,6 +99,8 @@
</template> </template>
</template> </template>
</t-table> </t-table>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="demandPage" v-model:page-size="demandPageSize" :total="demandTotal" />
</div> </div>
<!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) --> <!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) -->
@@ -126,15 +128,24 @@
:label="`${c.name}${c.category ? `(${c.category})` : ''}`" :label="`${c.name}${c.category ? `(${c.category})` : ''}`"
/> />
</t-select> </t-select>
<!-- 000158:提交时按名称精准匹配课程管理,未命中自动新增待核验课程 -->
<div class="form-hint">提交时按名称精准匹配课程管理;未匹配到将自动新增该课程(待审核),经课长/经理签核后方可发布</div>
</t-form-item> </t-form-item>
<t-form-item label="分类" name="category"> <t-form-item label="分类" name="category">
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" /> <t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
</t-form-item> </t-form-item>
<t-form-item label="所属部门" name="dept_id"> <t-form-item label="所属部门" name="dept_id">
<t-input :value="deptDisplay" disabled placeholder="提交时按提报人所在部门自动获取" /> <!-- 000158:所属部门必须为填报人本人部门,服务端强制按提报人部门落库 -->
<t-input :value="deptDisplay" disabled placeholder="自动带出提报人所在部门(不可修改)" />
</t-form-item> </t-form-item>
<t-form-item label="适合人员" name="post_scope"> <t-form-item label="适合人员" name="post_scope">
<t-input v-model="demandForm.post_scope" placeholder="可填写多个适合人员,用、或,分隔(选填)" /> <!-- 000159 部门多选口径:归属部门(可多选)或「全部」(互斥),自动建档随需求带入课程 -->
<t-select
v-model="demandSuitableList" clearable filterable multiple
placeholder="选择部门(可多选),或选「全部」(选填)" style="width: 100%"
>
<t-option v-for="opt in demandSuitableOptions" :key="opt" :value="opt" :label="opt" />
</t-select>
</t-form-item> </t-form-item>
<t-form-item label="计划培训月份" name="planned_month"> <t-form-item label="计划培训月份" name="planned_month">
<t-select <t-select
@@ -197,7 +208,7 @@
:autosize="{ minRows: 6 }" :autosize="{ minRows: 6 }"
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)" placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
/> />
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div> <div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配)或外部讲师姓名;部门列必须为导入人本人部门,留空默认本人部门,其余部门整批拒绝导入;课程按名称精准匹配课程管理,未匹配到自动新增该课程(待审核);导入后统一为「待核验」,由部门经理核验确认。</div>
<template #footer> <template #footer>
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button> <t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
</template> </template>
@@ -235,12 +246,14 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
import * as XLSX from 'xlsx' 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,
@@ -282,7 +295,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)
@@ -299,13 +315,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)
@@ -332,13 +350,35 @@ const demandForm = ref({
remark: '', remark: '',
}) })
// 适合人员多选值(000159 部门多选口径):form.post_scope 存「、」join 后的串,
// 选项交互走本数组;「全部」与具体部门互斥。
const demandSuitableList = ref<string[]>([])
const splitSuitable = (v: string) =>
(v || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
watch(demandSuitableList, (list, prev) => {
if (list.includes('全部') && list.length > 1) {
demandSuitableList.value = (prev || []).includes('全部') ? list.filter((v) => v !== '全部') : ['全部']
}
})
// 适合人员选项:全部 + 各部门名(存量自由文本值保留可选)
const demandSuitableOptions = computed(() => {
const opts = ['全部', ...depts.value.map((d) => d.name)]
for (const v of splitSuitable(demandForm.value.post_scope)) {
if (!opts.includes(v)) opts.push(v)
}
return opts
})
// 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改; // 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改;
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员) // 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
const onDemandCourseChange = (name: unknown) => { 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) demandForm.value.post_scope = course.suitable_members if (course.suitable_members) {
demandForm.value.post_scope = course.suitable_members
demandSuitableList.value = splitSuitable(course.suitable_members)
}
const lecturerValue = course.lecturer_id || course.lecturer_external || '' const lecturerValue = course.lecturer_id || course.lecturer_external || ''
if (lecturerValue) { if (lecturerValue) {
if (!lecturers.value.some((l) => l.id === lecturerValue)) { if (!lecturers.value.some((l) => l.id === lecturerValue)) {
@@ -481,9 +521,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) => {
@@ -500,6 +552,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()
} }
@@ -552,6 +611,7 @@ const onOpenDemandForm = () => {
lecturer: '', lecturer: '',
remark: '', remark: '',
} }
demandSuitableList.value = []
demandFormVisible.value = true demandFormVisible.value = true
} }
@@ -588,6 +648,8 @@ const onEditDemand = (row: TrainingDemand) => {
lecturer: lecturerValue, lecturer: lecturerValue,
remark: row.remark || '', remark: row.remark || '',
} }
// 适合人员多选回显(000159):落库串「、」join → 数组
demandSuitableList.value = splitSuitable(demandForm.value.post_scope)
demandFormVisible.value = true demandFormVisible.value = true
} }
@@ -599,10 +661,14 @@ const onSaveDemand = async () => {
saving.value = true saving.value = true
try { try {
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份; // 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名 // 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名;
// 适合人员多选 → 「、」join 落库(000159)
const { lecturer, planned_month, ...rest } = demandForm.value const { lecturer, planned_month, ...rest } = demandForm.value
rest.post_scope = demandSuitableList.value.join('、')
const month = Number(planned_month) || 0 const month = Number(planned_month) || 0
const isEdit = Boolean(demandForm.value.id) const isEdit = Boolean(demandForm.value.id)
// 课程管理中是否已有同名课程(000158:无则提交时自动新增待核验课程)
const courseExisted = libraryCourses.value.some((c) => c.name === demandForm.value.course_name)
await saveDemand({ await saveDemand({
...rest, ...rest,
...resolveLecturer(lecturer), ...resolveLecturer(lecturer),
@@ -612,7 +678,13 @@ const onSaveDemand = async () => {
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined, expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
year: selectedYear.value, year: selectedYear.value,
}) })
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待核验') MessagePlugin.success(
demandForm.value.id
? '需求已更新'
: courseExisted
? '需求已提交,待核验'
: `需求已提交,待核验;课程《${demandForm.value.course_name}》已自动新增到课程管理(待审核)`,
)
demandFormVisible.value = false demandFormVisible.value = false
loadAll() loadAll()
} catch (e: any) { } catch (e: any) {
@@ -668,8 +740,9 @@ const onImportDemands = async () => {
importDemandsVisible.value = false importDemandsVisible.value = false
importDemandsText.value = '' importDemandsText.value = ''
loadAll() loadAll()
} catch { } catch (e: any) {
MessagePlugin.error('导入失败,请检查格式') // 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
MessagePlugin.error(apiErrorMessage(e, '导入失败,请检查格式'))
} finally { } finally {
saving.value = false saving.value = false
} }
@@ -747,7 +820,8 @@ const onImportDemandExcel = async (e: Event) => {
let skippedRows = 0 let skippedRows = 0
let lecturerHits = 0 let lecturerHits = 0
let externalLecturers = 0 let externalLecturers = 0
let deptFromLecturer = 0 // 部门口径(000158):Excel 全部行必须为导入人本人部门,前端预检不过不提交
const deptViolations: string[] = []
// 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案), // 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案),
// 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示 // 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示
const ensureMembers = async () => { const ensureMembers = async () => {
@@ -763,24 +837,23 @@ const onImportDemandExcel = async (e: Event) => {
} }
} }
await ensureMembers() await ensureMembers()
dataRows.forEach((row) => { dataRows.forEach((row, idx) => {
const courseName = (row['课程名称'] || '').trim() const courseName = (row['课程名称'] || '').trim()
if (!courseName) { if (!courseName) {
skippedRows += 1 skippedRows += 1
return return
} }
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;未匹配留空 // 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;
// 000158:行部门必须为导入人本人部门——非空但未匹配到、或与本人部门
// 不一致即记违规,整批拒绝;部门列留空的行由后端默认导入人部门。
let deptId = '' let deptId = ''
let deptMatched = false
const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim() const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim()
if (deptName) { if (deptName) {
const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name)) const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
if (hit) { if (hit) deptId = hit.id
deptId = hit.id if (!deptId || deptId !== myDeptId.value) deptViolations.push(`第${idx + 1}行(${deptName})`)
deptMatched = true
}
} }
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名,行内部门未匹配时带出讲师部门; // 讲师:员工档案姓名精确匹配→关联并在列表带出姓名;
// 非系统员工→落外部讲师姓名,讲师列照常显示 // 非系统员工→落外部讲师姓名,讲师列照常显示
let lecturerId = '' let lecturerId = ''
let lecturerExternal = '' let lecturerExternal = ''
@@ -790,10 +863,6 @@ const onImportDemandExcel = async (e: Event) => {
if (hit && hit.user_id) { if (hit && hit.user_id) {
lecturerId = hit.user_id lecturerId = hit.user_id
lecturerHits += 1 lecturerHits += 1
if (!deptMatched && hit.dept_id) {
deptId = hit.dept_id
deptFromLecturer += 1
}
} else { } else {
lecturerExternal = lecturerName lecturerExternal = lecturerName
externalLecturers += 1 externalLecturers += 1
@@ -813,6 +882,7 @@ const onImportDemandExcel = async (e: Event) => {
lecturer_id: lecturerId, lecturer_id: lecturerId,
lecturer_external: lecturerExternal || undefined, lecturer_external: lecturerExternal || undefined,
dept_id: deptId, dept_id: deptId,
dept_name: deptName || undefined,
planned_time: plannedMonth.planned || undefined, planned_time: plannedMonth.planned || undefined,
expect_month: plannedMonth.month || undefined, expect_month: plannedMonth.month || undefined,
remark: (row['备注'] || '').trim(), remark: (row['备注'] || '').trim(),
@@ -822,24 +892,36 @@ const onImportDemandExcel = async (e: Event) => {
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称') MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
return return
} }
// 000158:存在非本人部门的行时整批拒绝(后端同口径兜底校验)
if (deptViolations.length) {
MessagePlugin.error(
`导入失败:${deptViolations.join('、')}部门与您所在部门(${myDeptName.value || '未知'})不一致,仅可导入本人部门的需求表`,
)
return
}
saving.value = true saving.value = true
try { try {
const imported = unwrap(await importDemands(items)) as { imported: number; notified?: number } | null const imported = unwrap(await importDemands(items)) as {
imported: number
notified?: number
courses_created?: number
} | null
MessagePlugin.success( MessagePlugin.success(
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` + `已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
(lecturerHits || externalLecturers (lecturerHits || externalLecturers
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}` ? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
: '') + : '') +
(deptFromLecturer ? `(其中 ${deptFromLecturer} 条部门按讲师带出)` : '') +
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') + (skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
(imported?.courses_created ? `,自动新增待审核课程 ${imported.courses_created} 门` : '') +
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''), (imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
) )
importDemandsVisible.value = false importDemandsVisible.value = false
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示 // 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
if (titleYear !== selectedYear.value) selectedYear.value = titleYear if (titleYear !== selectedYear.value) selectedYear.value = titleYear
loadAll() loadAll()
} catch { } catch (e: any) {
MessagePlugin.error('导入失败,请稍后重试') // 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
MessagePlugin.error(apiErrorMessage(e, '导入失败,请稍后重试'))
} finally { } finally {
saving.value = false saving.value = false
} }
@@ -956,6 +1038,11 @@ onMounted(() => {
} }
} }
// 表单项内提示文案(form-hint)统一另起一行展示在控件下方
.plan-panel {
.training-form-hints-below();
}
// 已确认行不做整行置灰: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) {
@@ -28,9 +28,21 @@
<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 分钟自动更新,旧码即时作废;
轮换由后端在轮询读取时惰性触发,本页每 10s 轻量轮询驱动) -->
<div class="sign-code-box__countdown" v-if="signCode && rotateRemainSec > 0">
{{ rotateRemainText }}后自动更新,旧码作废需重扫
</div>
<div class="sign-code-box__countdown is-stale" v-else-if="signCode">即将自动更新签到码…</div>
<t-button v-if="canReview" theme="primary" variant="outline" :loading="genLoading" @click="onGenCode"> <t-button v-if="canReview" theme="primary" variant="outline" :loading="genLoading" @click="onGenCode">
{{ signCode ? '刷新签到码' : '生成签到码' }} {{ signCode ? '刷新签到码' : '生成签到码' }}
</t-button> </t-button>
@@ -59,6 +71,15 @@
<div class="upload-card__hint">{{ uploading ? '上传中…' : '课程实录留证 · 每个 ≤ ' + VIDEO_MAX_MB + 'MB' }}</div> <div class="upload-card__hint">{{ uploading ? '上传中…' : '课程实录留证 · 每个 ≤ ' + VIDEO_MAX_MB + 'MB' }}</div>
</div> </div>
</template> </template>
<!-- 培训详情:回跳课程学习详情页(与课程详情页「培训签到」按钮互为出入口) -->
<div v-if="selectedCourseId" class="stat-card upload-card" role="button" tabindex="0" @click="goCourseDetail" @keydown.enter="goCourseDetail">
<div class="stat-card__label">培训详情</div>
<div class="upload-card__main">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v14"/><path d="M2 19h20"/><path d="M8 7h8M8 11h6"/></svg>
<span :title="courseName(selectedCourseId)">{{ courseName(selectedCourseId) }}</span>
</div>
<div class="upload-card__hint">查看课程课件 / 随堂考试详情</div>
</div>
</div> </div>
<input ref="photoInput" type="file" accept="image/*" multiple class="visually-hidden-input" @change="onEvidenceFiles($event, 'sign_photo')" /> <input ref="photoInput" type="file" accept="image/*" multiple class="visually-hidden-input" @change="onEvidenceFiles($event, 'sign_photo')" />
<input ref="videoInput" type="file" accept="video/*" multiple class="visually-hidden-input" @change="onEvidenceFiles($event, 'training_video')" /> <input ref="videoInput" type="file" accept="video/*" multiple class="visually-hidden-input" @change="onEvidenceFiles($event, 'training_video')" />
@@ -90,10 +111,12 @@
<!-- 签到明细 --> <!-- 签到明细 -->
<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 }">{{ memberLabel(row.member_id) }}</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 row.abnormal_flags || []" :key="f" theme="danger" variant="outline" size="small" class="flag-tag">{{ flagText(f) }}</t-tag>
@@ -105,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%">
@@ -150,8 +175,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next' import { MessagePlugin } from 'tdesign-vue-next'
import QRCode from 'qrcode' import QRCode from 'qrcode'
import { import {
@@ -178,10 +203,13 @@ 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()
const router = useRouter()
// 签到复核/代签:人事/课长(roles 已按权限组展开,经理自动命中) // 签到复核/代签:人事/课长(roles 已按权限组展开,经理自动命中)
const canReview = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor')) const canReview = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor'))
// 佐证上传/删除:人事/课长/讲师(与课件上传同口径) // 佐证上传/删除:人事/课长/讲师(与课件上传同口径)
@@ -197,10 +225,28 @@ const exportLoading = ref(false)
const sessions = ref<TrainingCourseSession[]>([]) const sessions = ref<TrainingCourseSession[]>([])
const courses = ref<TrainingCourse[]>([]) const courses = ref<TrainingCourse[]>([])
const selectedSessionId = ref('') const selectedSessionId = ref('')
// 当前选中场次的课程 id:「培训详情」卡片回跳课程学习详情页用(2026-11 需求)
const selectedCourseId = computed(
() => sessions.value.find((s) => s.id === selectedSessionId.value)?.course_id || '',
)
// 培训详情:携课程 id 跳「培训签到」页的同源落地页(课程学习详情)。
const goCourseDetail = () => {
if (!selectedCourseId.value) return
router.push({ path: `/platform/training/course/${selectedCourseId.value}` })
}
const signCode = ref<TrainingSignCode | null>(null) 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 },
@@ -218,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('')
@@ -227,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 {
@@ -236,10 +288,82 @@ 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 企微扫码需求) ----
// 后端在 GET sign-code 超过轮换窗口(rotation_sec,默认 5 分钟)时惰性轮换:
// 旧 token 挪入 prev(30s 宽限后彻底作废),新码即时生效。本页每 10s 轻量轮询
// sign-code(不带明细/佐证),token 变化经上方 watch 自动重绘二维码并提示重扫;
// 页面隐藏时暂停轮询(投屏不在展示态时不做无谓轮换)。
const rotateRemainSec = ref(0)
let rotateDisplayTimer: number | undefined
let rotatePollTimer: number | undefined
const fmtRemainText = (sec: number) => {
const m = Math.floor(sec / 60)
const s = sec % 60
return m > 0 ? `${m}分${String(s).padStart(2, '0')}秒` : `${s}秒`
}
const rotateRemainText = computed(() => fmtRemainText(rotateRemainSec.value))
const tickRotateRemain = () => {
const exp = signCode.value?.expire_at
rotateRemainSec.value = exp ? Math.max(0, Math.floor((new Date(exp).getTime() - Date.now()) / 1000)) : 0
}
const pollSignCode = async () => {
if (!selectedSessionId.value || document.hidden) return
try {
const next = unwrap<TrainingSignCode | null>(await getSignCode(selectedSessionId.value))
if (!next) return
if (next.token !== signCode.value?.token) {
// 仅在 token 变化时回写:watch(signCode) 会重绘二维码并提示重扫;
// token 未变时跳过赋值,避免每 10s 触发一次无谓重绘。
signCode.value = next
MessagePlugin.info('签到码已自动更新,旧码已作废,请提醒学员重新扫码')
}
} catch {
// 场次尚未生成签到码/网络抖动:静默,不打断投屏。
}
}
const startCodeRotation = () => {
stopCodeRotation()
tickRotateRemain()
rotateDisplayTimer = window.setInterval(tickRotateRemain, 1000)
rotatePollTimer = window.setInterval(pollSignCode, 10000)
}
const stopCodeRotation = () => {
if (rotateDisplayTimer) {
window.clearInterval(rotateDisplayTimer)
rotateDisplayTimer = undefined
}
if (rotatePollTimer) {
window.clearInterval(rotatePollTimer)
rotatePollTimer = undefined
}
}
watch(selectedSessionId, (sid) => {
if (sid) startCodeRotation()
else stopCodeRotation()
})
const flagText = (f: string) => ({ late: '迟到', outside: '定位异常', not_in_roster: '名单外' }[f] || f) const flagText = (f: string) => ({ late: '迟到', outside: '定位异常', not_in_roster: '名单外' }[f] || f)
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[]>([])
@@ -247,11 +371,12 @@ 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(' ')
const loadAll = async () => { const loadAll = async () => {
loading.value = true loading.value = true
@@ -267,10 +392,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
} }
@@ -282,6 +406,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),
@@ -464,7 +589,11 @@ watch(() => route.query.courseId, applyRouteCourse)
onMounted(async () => { onMounted(async () => {
await loadAll() await loadAll()
applyRouteCourse() applyRouteCourse()
// 签到码轮换:进页即启动(选中场次后 watch 也会重启,双保险覆盖异步加载)。
startCodeRotation()
}) })
onUnmounted(stopCodeRotation)
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@@ -518,6 +647,15 @@ onMounted(async () => {
padding: 8px; padding: 8px;
} }
&__meta { color: var(--td-text-color-placeholder); font-size: var(--app-text-sm); margin-bottom: 10px; } &__meta { color: var(--td-text-color-placeholder); font-size: var(--app-text-sm); margin-bottom: 10px; }
// 自动轮换倒计时(2026-11 需求):临期转警示色,提醒讲师学员需重扫。
&__countdown {
color: var(--td-brand-color);
font-size: var(--app-text-sm);
margin-bottom: 10px;
&.is-stale { color: var(--td-warning-color, #e37318); }
}
} }
.stat-cards { .stat-cards {
@@ -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
}
+14
View File
@@ -171,6 +171,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);
+82 -7
View File
@@ -65,15 +65,25 @@ func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, i
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。 // employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
// users/org_depts 联查在此一并挂上:keyword 需要按姓名/部门名过滤,且 Count
// 与列表共用同一过滤,联查必须两边一致(users/org_depts 对档案均为 1:1,
// 不影响 Count 语义)。
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB { func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).Where("org_employees.tenant_id = ?", tenantID) tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
Where("org_employees.tenant_id = ?", tenantID).
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
if q != nil { if q != nil {
if q.DeptID != "" { if q.DeptID != "" {
tx = tx.Where("org_employees.dept_id = ?", q.DeptID) tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
} }
if q.Keyword != "" { if q.Keyword != "" {
tx = tx.Where("org_employees.employee_no ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?", // 按姓名/工号/部门名/岗位模糊查找;姓名取真实姓名(display_name)
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%") // 回退平台账号(username),与列表展示口径一致。
tx = tx.Where(
"org_employees.employee_no ILIKE ? OR COALESCE(NULLIF(u.display_name, ''), u.username, '') ILIKE ? "+
"OR COALESCE(dp.name, '') ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
} }
} }
return tx return tx
@@ -102,9 +112,7 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
tx := filter(). tx := filter().
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的 // user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
// username 存工号,真实姓名在 display_name(见 000143 迁移)。 // username 存工号,真实姓名在 display_name(见 000143 迁移)。
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`). Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`)
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
if moduleKey != "" { if moduleKey != "" {
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。 // 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name, tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
@@ -112,8 +120,9 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey) Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
} }
var employees []*types.OrgEmployee var employees []*types.OrgEmployee
// 新增成员置顶(时间倒序):最新建档/导入的员工排在列表最前。
err := tx. err := tx.
Order("org_employees.created_at ASC"). Order("org_employees.created_at DESC").
Offset((page - 1) * pageSize).Limit(pageSize). Offset((page - 1) * pageSize).Limit(pageSize).
Find(&employees).Error Find(&employees).Error
return employees, total, err return employees, total, err
@@ -141,6 +150,27 @@ func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID
return &m, nil return &m, nil
} }
// InsertEmployeesIfAbsent 自动入册专用:成员加入空间时补建员工档案。
// 与 UpsertEmployees(导入语义,整行覆盖)不同,本方法只补空不覆盖——
// 已有档案的工号/部门仅在为空时用新值回填(如 Casdoor 后同步到部门),
// 人工维护过(或 OA 同步)的字段一律保留。
func (r *orgCenterRepository) InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error {
if len(employees) == 0 {
return nil
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
// 档案已有工号/部门时不覆盖(空串/空 id 视为未维护,由新值补齐)。
"employee_no": gorm.Expr("COALESCE(NULLIF(org_employees.employee_no, ''), EXCLUDED.employee_no)"),
"dept_id": gorm.Expr("COALESCE(NULLIF(org_employees.dept_id, ''), EXCLUDED.dept_id)"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(&employees).Error
}
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id). // UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error { func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
if len(employees) == 0 { if len(employees) == 0 {
@@ -218,6 +248,31 @@ func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint
return users, err return users, err
} }
// ListAdoptableUsers lists the tenant's active members whose home tenant
// (users.tenant_id) is not this workspace — the preview source for
// 「收编到本空间」. 归属列为 NULL(无归属账号)的成员同样是候选:Postgres 的
// `NULL != x` 不命中,须 COALESCE 兜底(仓库测试跑在 SQLite 上,两者兼容)。
// 名册 join 与 ListTenantUsers 同口径;home 租户名联查 tenants(带软删过滤)
// 供 UI 确认来源空间。
func (r *orgCenterRepository) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) {
var users []*types.OrgAdoptableUser
err := r.db.WithContext(ctx).
Table("users u").
Select(`u.id, u.username, u.email, u.display_name,
COALESCE(u.tenant_id, 0) AS home_tenant_id,
COALESCE(ht.name, '') AS home_tenant_name,
(m.id IS NOT NULL) AS in_roster`).
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
Joins("LEFT JOIN org_employees m ON m.user_id = u.id AND m.tenant_id = ? AND m.deleted_at IS NULL", tenantID).
Joins("LEFT JOIN tenants ht ON ht.id = u.tenant_id AND ht.deleted_at IS NULL").
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
Where("COALESCE(u.tenant_id, 0) != ?", tenantID).
Order("u.created_at ASC").
Scan(&users).Error
return users, err
}
// GetUsernamesByUserIDs resolves platform accounts (users.username) for the // GetUsernamesByUserIDs resolves platform accounts (users.username) for the
// given user IDs within the tenant — used to backfill employee_no on import // given user IDs within the tenant — used to backfill employee_no on import
// (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。 // (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。
@@ -244,6 +299,26 @@ func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantI
return m, nil return m, nil
} }
// GetRosterUserInfos resolves the roster-relevant user fields (平台账号 + Casdoor
// 同步部门) for the given user IDs within the tenant — source for auto-creating
// employee profiles when members join (EnsureEmployeesForUsers 的取数口径与
// GetUsernamesByUserIDs 一致:本空间 active 成员)。
func (r *orgCenterRepository) GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
if len(userIDs) == 0 {
return nil, nil
}
var users []*types.TrainingUserInfo
err := r.db.WithContext(ctx).
Table("users u").
Select("u.id, u.username, u.dept_code, u.dept_name").
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
Where("u.id IN ?", userIDs).
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
Scan(&users).Error
return users, err
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 模块角色绑定 // 模块角色绑定
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -0,0 +1,104 @@
package repository
import (
"context"
"testing"
"time"
"academy/internal/types"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// 收编预览数据源回归:ListAdoptableUsers 须列出「归属空间不在本空间」的活跃
// 成员,含两类边界——归属列为 NULL 的无归属账号(Postgres 的 `NULL != x` 不
// 命中,COALESCE 兜底)与归属本空间者不列。名册标记与 home 租户名供 UI 确认。
func TestListAdoptableUsers(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:org-adoptable?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := db.AutoMigrate(&types.User{}, &types.Tenant{}, &types.TenantMember{}, &types.OrgEmployee{}); err != nil {
t.Fatalf("migrate schema: %v", err)
}
base := time.Date(2026, 11, 24, 3, 0, 0, 0, time.UTC)
mkUser := func(id string, home uint64, offset time.Duration) *types.User {
return &types.User{
ID: id, Username: id, Email: id + "@casdoor.local",
TenantID: home, IsActive: true,
CreatedAt: base.Add(offset), UpdatedAt: base.Add(offset),
}
}
// personal-home:归属个人空间 3,典型收编对象;tenantless:归属 NULL;
// local:归属本空间 2(不列);inactive:停用账号不列。
for _, u := range []*types.User{
mkUser("personal-home", 3, 0),
mkUser("tenantless", 0, time.Hour),
mkUser("local", 2, 2*time.Hour),
mkUser("inactive", 4, 3*time.Hour),
} {
if err := db.Create(u).Error; err != nil {
t.Fatalf("insert user %s: %v", u.ID, err)
}
}
// 停用账号以软删模拟(与 GetUsersByIDs/ListTenantUsers 的可见口径一致)。
if err := db.Delete(&types.User{}, "id = ?", "inactive").Error; err != nil {
t.Fatalf("soft-delete user: %v", err)
}
for _, m := range []*types.TenantMember{
{UserID: "personal-home", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base},
{UserID: "tenantless", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(time.Hour)},
{UserID: "local", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(2 * time.Hour)},
{UserID: "inactive", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(3 * time.Hour)},
} {
if err := db.Create(m).Error; err != nil {
t.Fatalf("insert membership %s: %v", m.UserID, err)
}
}
if err := db.Create(&types.Tenant{ID: 3, Name: "26080007's Workspace", Status: "active"}).Error; err != nil {
t.Fatalf("insert home tenant: %v", err)
}
if err := db.Create(&types.OrgEmployee{
TenantID: 2, UserID: "personal-home", EmployeeNo: "26080007", Status: "active",
}).Error; err != nil {
t.Fatalf("insert roster entry: %v", err)
}
repo := &orgCenterRepository{db: db}
users, err := repo.ListAdoptableUsers(context.Background(), 2)
if err != nil {
t.Fatalf("ListAdoptableUsers: %v", err)
}
byID := map[string]*types.OrgAdoptableUser{}
for _, u := range users {
byID[u.ID] = u
}
if len(users) != 2 {
t.Fatalf("want exactly personal-home + tenantless, got %+v", users)
}
if u := byID["personal-home"]; u == nil {
t.Fatal("personal-home missing from adoptable list")
} else {
if u.HomeTenantID != 3 || u.HomeTenantName != "26080007's Workspace" {
t.Fatalf("personal-home home = %d/%q, want 3/26080007's Workspace", u.HomeTenantID, u.HomeTenantName)
}
if !u.InRoster {
t.Fatal("personal-home InRoster = false, want true")
}
if u.Username != "personal-home" || u.Email != "personal-home@casdoor.local" {
t.Fatalf("personal-home display fields wrong: %+v", u)
}
}
if u := byID["tenantless"]; u == nil {
t.Fatal("tenantless (NULL home) missing from adoptable list — COALESCE guard failed")
} else if u.HomeTenantID != 0 || u.HomeTenantName != "" {
t.Fatalf("tenantless home should be 0/'', got %d/%q", u.HomeTenantID, u.HomeTenantName)
}
for _, absent := range []string{"local", "inactive"} {
if byID[absent] != nil {
t.Fatalf("user %s must not appear in adoptable list", absent)
}
}
}
@@ -48,6 +48,49 @@ func (r *trainingRepository) GetMemberByUserID(ctx context.Context, tenantID uin
return &m, nil return &m, nil
} }
// GetMemberByWecomUserid 企微免登反查(2026-11 扫码签到):按绑定定位培训档案。
func (r *trainingRepository) GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND wecom_userid = ?", tenantID, wecomUserid).
First(&m).Error; err != nil {
return nil, err
}
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):
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
// 同一组织的人员不因所在工作区不同而看不到企业培训。无档案返回 0,nil。
func (r *trainingRepository) FindArchiveTenantID(ctx context.Context, userID string) (uint64, error) {
var tenantIDs []uint64
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
Where("user_id = ? AND status = ?", userID, "active").
Order("created_at ASC").Limit(1).
Pluck("tenant_id", &tenantIDs).Error
if err != nil {
return 0, err
}
if len(tenantIDs) == 0 {
return 0, nil
}
return tenantIDs[0], nil
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 学习/积分/规则/通知 // 学习/积分/规则/通知
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -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,6 +68,24 @@ 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):仅已发布 + 课程权限覆盖调用方
// (000163:perm 两列精确命中;存量课程沿用 suitable_members 老口径)。
if q.CatalogOnly {
tx = tx.Where("tr_course_library.publish_status = ?", "published")
cond, args := courseLibraryPermissionCond(q)
tx = tx.Where(cond, args...)
}
// 课程权限过滤(000163):计划选课/无维护角色视图按调用方部门+人员收窄
// (与 catalog 同一匹配口径,handler 按视图注入调用方身份与放行项)。
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
if err := tx.Count(&total).Error; err != nil { if err := tx.Count(&total).Error; err != nil {
@@ -48,8 +103,10 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
var items []*types.TrainingCourseLibrary var items []*types.TrainingCourseLibrary
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列); // lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
// owner_dept_name 联查部门名(所属部门存 org_depts id); // owner_dept_name 联查部门名(所属部门存 org_depts id);
// creator_name 联查创建人姓名(display_name 优先,回退 username 工号)。 // 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"). // 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 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 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"). Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
@@ -59,6 +116,19 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
return items, total, err return items, total, err
} }
// FindCourseLibraryByName fetches one course-library item by exact course name
// (需求侧课程自动匹配,000158:按课程名称精准查找,同名存量取最早一条)。
func (r *trainingRepository) FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error) {
var item types.TrainingCourseLibrary
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND name = ?", tenantID, name).
Order("created_at ASC").
First(&item).Error; err != nil {
return nil, err
}
return &item, nil
}
// GetCourseLibraryItem fetches one course-library item. // GetCourseLibraryItem fetches one course-library item.
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) { func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
var item types.TrainingCourseLibrary var item types.TrainingCourseLibrary
@@ -73,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
@@ -88,6 +178,9 @@ 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,
"category": item.Category, "category": item.Category,
"type": item.Type, "type": item.Type,
"mode": item.Mode, "mode": item.Mode,
@@ -100,6 +193,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"
@@ -119,6 +120,7 @@ func (r *trainingRepository) UpdateDemand(ctx context.Context, demand *types.Tra
"lecturer_id": demand.LecturerID, "lecturer_id": demand.LecturerID,
"lecturer_external": demand.LecturerExternal, "lecturer_external": demand.LecturerExternal,
"course_name": demand.CourseName, "course_name": demand.CourseName,
"library_course_id": demand.LibraryCourseID,
"plant": demand.Plant, "plant": demand.Plant,
"category": demand.Category, "category": demand.Category,
"session_count": demand.SessionCount, "session_count": demand.SessionCount,
@@ -441,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
@@ -527,6 +559,31 @@ func (r *trainingRepository) CountEnrolledMembersByCourse(ctx context.Context, t
return out, nil return out, nil
} }
// CountEnrolledMembersByCourseID 单课程的场次学员名单人数(发布必填校验用,
// 000161:跨场次名单去重成员数;与 CountEnrolledMembersByCourse 同口径)。
func (r *trainingRepository) CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error) {
var cnt int64
err := r.db.WithContext(ctx).
Table("tr_enrollments e").
Joins("JOIN tr_course_sessions s ON s.id = e.session_id AND s.tenant_id = e.tenant_id AND s.deleted_at IS NULL").
Where("e.tenant_id = ? AND s.course_id = ?", tenantID, courseID).
Count(&cnt).Error
return int(cnt), err
}
// ListMyEnrolledCourseIDs 当前成员经场次学员名单报名的课程 id 去重集合
// (我的培训「我参加」判定数据源)。名单为软删(ReplaceEnrollments 移除即置
// deleted_at),故须过滤 e.deleted_at;场次软删行同样不计。
func (r *trainingRepository) ListMyEnrolledCourseIDs(ctx context.Context, tenantID uint64, memberID string) ([]string, error) {
ids := []string{}
err := r.db.WithContext(ctx).
Table("tr_enrollments e").
Joins("JOIN tr_course_sessions s ON s.id = e.session_id AND s.tenant_id = e.tenant_id AND s.deleted_at IS NULL").
Where("e.tenant_id = ? AND e.member_id = ? AND e.deleted_at IS NULL", tenantID, memberID).
Distinct().Pluck("s.course_id", &ids).Error
return ids, err
}
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(去重成员集合): // CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(去重成员集合):
// 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷 // 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷
// (session 为空时经 paper→bank→course 兜底)两条路径。 // (session 为空时经 paper→bank→course 兜底)两条路径。
@@ -725,18 +782,22 @@ func (r *trainingRepository) UpdateMaterial(ctx context.Context, material *types
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// UpsertSignCode creates or refreshes the session's sign-in code. // UpsertSignCode creates or refreshes the session's sign-in code.
// 2026-11 轮换需求:轮换时新行携带 prev_token/prev_expire_at(旧码宽限用),
// 一并覆盖,旧 token 即时退出当前码位。
func (r *trainingRepository) UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error { func (r *trainingRepository) UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error {
return r.db.WithContext(ctx). return r.db.WithContext(ctx).
Clauses(clause.OnConflict{ Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "session_id"}}, Columns: []clause.Column{{Name: "tenant_id"}, {Name: "session_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{ DoUpdates: clause.Assignments(map[string]interface{}{
"token": gorm.Expr("EXCLUDED.token"), "token": gorm.Expr("EXCLUDED.token"),
"expire_at": gorm.Expr("EXCLUDED.expire_at"), "expire_at": gorm.Expr("EXCLUDED.expire_at"),
"geo_lat": gorm.Expr("EXCLUDED.geo_lat"), "prev_token": gorm.Expr("EXCLUDED.prev_token"),
"geo_lng": gorm.Expr("EXCLUDED.geo_lng"), "prev_expire_at": gorm.Expr("EXCLUDED.prev_expire_at"),
"geo_radius": gorm.Expr("EXCLUDED.geo_radius"), "geo_lat": gorm.Expr("EXCLUDED.geo_lat"),
"created_by": gorm.Expr("EXCLUDED.created_by"), "geo_lng": gorm.Expr("EXCLUDED.geo_lng"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"), "geo_radius": gorm.Expr("EXCLUDED.geo_radius"),
"created_by": gorm.Expr("EXCLUDED.created_by"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}), }),
}). }).
Create(code).Error Create(code).Error
@@ -764,6 +825,19 @@ func (r *trainingRepository) GetSignCodeByToken(ctx context.Context, tenantID ui
return &c, nil return &c, nil
} }
// GetSignCodeByTokenGlobal 匿名扫码入口按 token 全局定位签到码(不带租户条件,
// 租户由码行反解):命中当前码或轮换宽限中的前码(prev_token)。表按
// (tenant, session) 唯一,行数极小,OR 扫描无性能顾虑。
func (r *trainingRepository) GetSignCodeByTokenGlobal(ctx context.Context, token string) (*types.TrainingSignCode, error) {
var c types.TrainingSignCode
if err := r.db.WithContext(ctx).
Where("(token = ? OR prev_token = ?) AND deleted_at IS NULL", token, token).
Order("created_at DESC").First(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// UpsertSignRecord stores one sign-in (unique per session+member). // UpsertSignRecord stores one sign-in (unique per session+member).
func (r *trainingRepository) UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error { func (r *trainingRepository) UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error {
return r.db.WithContext(ctx). return r.db.WithContext(ctx).
@@ -782,6 +856,18 @@ func (r *trainingRepository) GetSignRecord(ctx context.Context, tenantID uint64,
return &rec, nil return &rec, nil
} }
// GetSignRecordByNonce 防重放(2026-11 扫码签到):nonce 已用过则拒绝。
// 调用方保证 nonce 非空(空 nonce 不查,避免命中历史空值行)。
func (r *trainingRepository) GetSignRecordByNonce(ctx context.Context, tenantID uint64, nonce string) (*types.TrainingSignRecord, error) {
var rec types.TrainingSignRecord
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND nonce = ? AND deleted_at IS NULL", tenantID, nonce).
First(&rec).Error; err != nil {
return nil, err
}
return &rec, nil
}
// GetSignRecordByID fetches one record by ID (复核入口)。 // GetSignRecordByID fetches one record by ID (复核入口)。
func (r *trainingRepository) GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error) { func (r *trainingRepository) GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error) {
var rec types.TrainingSignRecord var rec types.TrainingSignRecord
+9 -2
View File
@@ -119,9 +119,16 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
// 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default // 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default
// 优先,否则该类型第一个 active)。fail-open:解析不到保持为空, // 优先,否则该类型第一个 active)。fail-open:解析不到保持为空,
// 运行时的 "chat model is not configured" 报错行为与现状一致。 // 运行时的 "chat model is not configured" 报错行为与现状一致。
if strings.TrimSpace(agent.Config.ModelID) == "" && s.modelService != nil { // ReRank 同口径兜底:无可用重排模型时保持为空(按需运行,不阻断)。
if s.modelService != nil &&
(strings.TrimSpace(agent.Config.ModelID) == "" || strings.TrimSpace(agent.Config.RerankModelID) == "") {
if models, err := s.modelService.ListModels(ctx); err == nil { if models, err := s.modelService.ListModels(ctx); err == nil {
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA) if strings.TrimSpace(agent.Config.ModelID) == "" {
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
}
if strings.TrimSpace(agent.Config.RerankModelID) == "" {
agent.Config.RerankModelID = PickDefaultModelID(models, types.ModelTypeRerank)
}
} else { } else {
logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err) logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err)
} }
+207 -2
View File
@@ -2,7 +2,10 @@ package service
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"strings"
"time"
"academy/internal/errors" "academy/internal/errors"
"academy/internal/logger" "academy/internal/logger"
@@ -10,16 +13,29 @@ import (
"academy/internal/types/interfaces" "academy/internal/types/interfaces"
"github.com/google/uuid" "github.com/google/uuid"
) )
// orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。 // orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。
// 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色, // 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色,
// 部门/岗位/姓名只维护一份。 // 部门/岗位/姓名只维护一份。
type orgCenterService struct { type orgCenterService struct {
repo interfaces.OrgCenterRepository repo interfaces.OrgCenterRepository
// 收编归属空间(登录默认落点)所需依赖。依赖仓库(UserRepository/
// TenantMemberRepository)而非服务:tenantMemberService 已反向依赖本服务,
// userService 又依赖 memberService,引用服务层会成 DI 环。audit 可空
// (nil ⇒ 不写审计,业务照常);users/members 为 nil 时收编接口不可用。
users interfaces.UserRepository
members interfaces.TenantMemberRepository
audit interfaces.AuditLogService
} }
// NewOrgCenterService constructs the org center service. // NewOrgCenterService constructs the org center service.
func NewOrgCenterService(repo interfaces.OrgCenterRepository) interfaces.OrgCenterService { func NewOrgCenterService(
return &orgCenterService{repo: repo} repo interfaces.OrgCenterRepository,
users interfaces.UserRepository,
members interfaces.TenantMemberRepository,
audit interfaces.AuditLogService,
) interfaces.OrgCenterService {
return &orgCenterService{repo: repo, users: users, members: members, audit: audit}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -161,6 +177,66 @@ func firstDuplicateEmployeeNo(employees []*types.OrgEmployee) string {
return "" return ""
} }
// EnsureEmployeesForUsers 成员加入空间时自动入册(需求:平台新增成员自动添加
// 到组织架构并匹配部门):按平台账号补建员工档案,部门按 Casdoor 同步字段
// 自动匹配(dept_code 精确命中优先,dept_name 兜底;匹配范式与 Casdoor 同步
// syncDepts 一致:小写去空格精确匹配)。档案已存在的成员跳过(仅补空),人工
// 维护字段不被覆盖。fail-open:入册是成员加入的伴生动作,失败只记日志,
// 不阻断成员关系本身。
func (s *orgCenterService) EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error {
if len(userIDs) == 0 {
return nil
}
users, err := s.repo.GetRosterUserInfos(ctx, tenantID, userIDs)
if err != nil {
return err
}
if len(users) == 0 {
return nil
}
depts, err := s.repo.ListDepts(ctx, tenantID)
if err != nil {
return err
}
byCode := make(map[string]string, len(depts))
byName := make(map[string]string, len(depts))
for _, d := range depts {
if code := strings.ToLower(strings.TrimSpace(d.Code)); code != "" {
byCode[code] = d.ID
}
if name := strings.ToLower(strings.TrimSpace(d.Name)); name != "" {
if _, exists := byName[name]; !exists {
byName[name] = d.ID // 首见优先,与 ListDepts 的 sort/created_at 序一致
}
}
}
employees := make([]*types.OrgEmployee, 0, len(users))
for _, u := range users {
deptID := ""
if code := strings.ToLower(strings.TrimSpace(u.DeptCode)); code != "" {
deptID = byCode[code]
}
if deptID == "" {
if name := strings.ToLower(strings.TrimSpace(u.DeptName)); name != "" {
deptID = byName[name]
}
}
employees = append(employees, &types.OrgEmployee{
ID: orgCenterNewID(),
TenantID: tenantID,
UserID: u.ID,
EmployeeNo: u.Username, // 工号 = 平台账号(与导入回填同约定)
DeptID: deptID, // 未匹配到已维护部门时留空,可后续手动修改
Status: "active",
})
}
if err := s.repo.InsertEmployeesIfAbsent(ctx, employees); err != nil {
return err
}
logger.Infof(ctx, "[OrgCenter] members auto-rostered, tenant=%d count=%d", tenantID, len(employees))
return nil
}
// UpdateEmployee updates one employee profile. // UpdateEmployee updates one employee profile.
func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) { func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) {
if employee.ID == "" { if employee.ID == "" {
@@ -199,6 +275,135 @@ func (s *orgCenterService) ListTenantUsers(ctx context.Context, tenantID uint64)
return s.repo.ListTenantUsers(ctx, tenantID) return s.repo.ListTenantUsers(ctx, tenantID)
} }
// ---------------------------------------------------------------------------
// 收编归属空间(登录默认落点)
// ---------------------------------------------------------------------------
// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。
func (s *orgCenterService) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) {
return s.repo.ListAdoptableUsers(ctx, tenantID)
}
// AdoptHomeTenant 把指定成员的归属空间(users.tenant_id,登录/refresh 默认落点)
// 批量收编为本空间。场景:员工首登自动开通个人空间(auth.default_tenant_mode
// =create_personal 默认),归属指针停在个人空间,登录后看到的组织架构/培训
// 数据是个人空间里那份空数据;管理员在本空间维护好组织架构后,用收编把成员
// 的默认落点改回本空间。语义:
// - 只动归属指针与「最近活跃租户」偏好,成员关系/角色/个人空间数据都不变,
// 成员仍可经空间切换器自行改回,非破坏性;
// - 仅收编本空间活跃成员(逐条校验,缺失跳过并回传原因,不整批失败);
// - 跨空间账号(CanAccessAllTenants)不自动收编——其落点是刻意配置;
// - 同步「最近活跃租户」偏好指向本空间:登录路径(resolveLoginTenantID)
// 优先读偏好,只改归属不改偏好时,切过空间的成员下次登录仍落回旧空间;
// - 收编成功的成员补跑一次自动入册(仅补空、幂等),把同步部门带进名册;
// - 已有会话不受影响,自下次登录/refresh 起落到本空间。
func (s *orgCenterService) AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error) {
if tenantID == 0 {
return nil, errors.NewBadRequestError("缺少目标空间")
}
if len(userIDs) == 0 {
return nil, errors.NewBadRequestError("请选择要收编的成员")
}
if s.users == nil || s.members == nil {
return nil, errors.NewInternalServerError("收编功能不可用:依赖服务未装配")
}
result := &types.OrgAdoptResult{Skipped: []*types.OrgAdoptSkip{}}
adopted := make([]string, 0, len(userIDs))
for _, userID := range userIDs {
if s.adoptOneHomeTenant(ctx, tenantID, userID, result) == nil {
adopted = append(adopted, userID)
}
}
result.Adopted = len(adopted)
// 收编成功者补跑自动入册(fail-open,与成员加入路径同约定):名册缺行时
// 按平台账号补建,dept_code/dept_name 命中已维护部门时自动匹配。失败只
// 告警:归属指针已落库,名册可由成员加入路径或手动导入补齐。
if len(adopted) > 0 {
if err := s.EnsureEmployeesForUsers(ctx, tenantID, adopted); err != nil {
logger.Warnf(ctx, "[OrgCenter] adopt home tenant: auto-roster backfill failed (adoption kept): tenant=%d err=%v",
tenantID, err)
}
}
s.emitAdoptAudit(ctx, tenantID, len(adopted), result.Skipped)
logger.Infof(ctx, "[OrgCenter] home tenants adopted, tenant=%d adopted=%d skipped=%d",
tenantID, len(adopted), len(result.Skipped))
return result, nil
}
// adoptOneHomeTenant 收编单个成员;返回 nil 表示收编成功,否则为跳过记录
// (已追加进 result.Skipped,原因逐条回传 UI)。
func (s *orgCenterService) adoptOneHomeTenant(ctx context.Context, tenantID uint64, userID string, result *types.OrgAdoptResult) *types.OrgAdoptSkip {
skipWith := func(u *types.User, reason string) *types.OrgAdoptSkip {
entry := &types.OrgAdoptSkip{UserID: userID, Reason: reason}
if u != nil {
entry.Username = u.Username
entry.DisplayName = u.DisplayName
}
result.Skipped = append(result.Skipped, entry)
return entry
}
user, err := s.users.GetUserByID(ctx, userID)
if err != nil || user == nil {
// GetUserByID 带软删过滤:已删除账号在此按不存在处理。
return skipWith(nil, "平台账号不存在")
}
if !user.IsActive {
return skipWith(user, "账号已停用")
}
if user.CanAccessAllTenants {
return skipWith(user, "跨空间账号不自动收编")
}
if user.TenantID == tenantID {
return skipWith(user, "归属空间已是本空间")
}
member, err := s.members.Get(ctx, userID, tenantID)
if err != nil {
return skipWith(user, "查询成员关系失败")
}
if member == nil || member.Status != types.TenantMemberStatusActive {
return skipWith(user, "非本空间成员,请先邀请或批量导入加入")
}
// 归属指针 + 最近活跃租户偏好一起指向本空间(见 AdoptHomeTenant 语义注释)。
user.TenantID = tenantID
user.Preferences.LastActiveTenantID = &tenantID
user.UpdatedAt = time.Now()
if err := s.users.UpdateUser(ctx, user); err != nil {
return skipWith(user, "写入归属空间失败:"+err.Error())
}
return nil
}
// emitAdoptAudit 写一条批量收编审计(best-effort:audit 不可用不阻断,
// 与 tenantMemberService.emitAudit 同约定)。单批一条,Details 记名单与
// 统计,供审计侧对账。
func (s *orgCenterService) emitAdoptAudit(ctx context.Context, tenantID uint64, adopted int, skipped []*types.OrgAdoptSkip) {
if s.audit == nil {
return
}
ids := make([]string, 0, len(skipped))
for _, sk := range skipped {
ids = append(ids, sk.UserID)
}
details, err := json.Marshal(map[string]any{
"user_ids": ids,
"adopted": adopted,
"skipped": len(skipped),
})
if err != nil {
return
}
actor, _ := types.UserIDFromContext(ctx)
_ = s.audit.Log(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: actor,
ActorRole: string(types.TenantRoleFromContext(ctx)),
Action: types.AuditActionMemberHomeAdopted,
TargetType: "tenant_member",
Outcome: types.AuditOutcomeSuccess,
Details: details,
})
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 模块角色绑定 // 模块角色绑定
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -0,0 +1,185 @@
package service
import (
"context"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// 收编归属空间(AdoptHomeTenant):把成员的登录默认落点(users.tenant_id +
// 最近活跃租户偏好)批量改指本空间。场景回归:员工首登开了个人空间后,登录
// 落在个人空间,看不到本空间维护的组织架构;收编只动归属指针,成员关系与
// 个人空间数据不变。
// fakeAdoptOrgRepo 组织中心仓库桩:入册补建(EnsureEmployeesForUsers)路径。
type fakeAdoptOrgRepo struct {
interfaces.OrgCenterRepository
roster []*types.OrgEmployee // InsertEmployeesIfAbsent 收到的补建行
userInfos []*types.TrainingUserInfo
}
func (f *fakeAdoptOrgRepo) ListDepts(context.Context, uint64) ([]*types.OrgDept, error) {
return []*types.OrgDept{{ID: "d1", Name: "生产一部", Code: "D01"}}, nil
}
func (f *fakeAdoptOrgRepo) GetRosterUserInfos(_ context.Context, _ uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
byID := map[string]*types.TrainingUserInfo{}
for _, u := range f.userInfos {
byID[u.ID] = u
}
out := make([]*types.TrainingUserInfo, 0, len(userIDs))
for _, id := range userIDs {
if u, ok := byID[id]; ok {
out = append(out, u)
}
}
return out, nil
}
func (f *fakeAdoptOrgRepo) InsertEmployeesIfAbsent(_ context.Context, employees []*types.OrgEmployee) error {
f.roster = append(f.roster, employees...)
return nil
}
// fakeAdoptUserRepo 用户仓库桩:收编读改写 users.tenant_id / 偏好。
type fakeAdoptUserRepo struct {
interfaces.UserRepository
users map[string]*types.User
updated []*types.User
}
func (f *fakeAdoptUserRepo) GetUserByID(_ context.Context, id string) (*types.User, error) {
if u, ok := f.users[id]; ok {
return u, nil
}
return nil, nil
}
func (f *fakeAdoptUserRepo) UpdateUser(_ context.Context, u *types.User) error {
f.updated = append(f.updated, u)
return nil
}
// fakeAdoptMemberRepo 成员仓库桩:收编前校验目标空间活跃成员关系。
type fakeAdoptMemberRepo struct {
interfaces.TenantMemberRepository
members map[string]*types.TenantMember // key: user_id(目标空间)
}
func (f *fakeAdoptMemberRepo) Get(_ context.Context, userID string, _ uint64) (*types.TenantMember, error) {
if m, ok := f.members[userID]; ok {
return m, nil
}
return nil, nil
}
func newAdoptService(org *fakeAdoptOrgRepo, users *fakeAdoptUserRepo, members *fakeAdoptMemberRepo) interfaces.OrgCenterService {
return NewOrgCenterService(org, users, members, nil)
}
func TestAdoptHomeTenantMovesHomeAndPreference(t *testing.T) {
org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{
{ID: "u-sun", Username: "26080007", DeptCode: "D01", DeptName: "生产一部"},
}}
pref := uint64(9) // 旧偏好指向个人空间:收编必须一并改指,否则登录仍落旧空间
users := &fakeAdoptUserRepo{users: map[string]*types.User{
"u-sun": {ID: "u-sun", Username: "26080007", IsActive: true, TenantID: 9,
Preferences: types.UserPreferences{LastActiveTenantID: &pref}},
}}
members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{
"u-sun": {UserID: "u-sun", TenantID: 2, Status: types.TenantMemberStatusActive},
}}
svc := newAdoptService(org, users, members)
result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{"u-sun"})
if err != nil {
t.Fatalf("AdoptHomeTenant: %v", err)
}
if result.Adopted != 1 || len(result.Skipped) != 0 {
t.Fatalf("unexpected result: adopted=%d skipped=%+v", result.Adopted, result.Skipped)
}
saved := users.updated[0]
if saved.TenantID != 2 {
t.Fatalf("home tenant not moved: %d", saved.TenantID)
}
if saved.Preferences.LastActiveTenantID == nil || *saved.Preferences.LastActiveTenantID != 2 {
t.Fatalf("LastActiveTenantID not pointed at target: %+v", saved.Preferences.LastActiveTenantID)
}
// 收编成功者补跑自动入册:名册补建且部门按 dept_code 匹配。
if len(org.roster) != 1 || org.roster[0].UserID != "u-sun" || org.roster[0].DeptID != "d1" {
t.Fatalf("roster backfill missing or dept unmatched: %+v", org.roster)
}
}
func TestAdoptHomeTenantSkipsNonMembersAndSuperusers(t *testing.T) {
org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{
{ID: "u-in", Username: "26080007"},
}}
users := &fakeAdoptUserRepo{users: map[string]*types.User{
"u-in": {ID: "u-in", Username: "26080007", IsActive: true, TenantID: 9},
"u-super": {ID: "u-super", Username: "admin", IsActive: true, CanAccessAllTenants: true},
"u-out": {ID: "u-out", Username: "26010001", IsActive: true, TenantID: 9},
"u-off": {ID: "u-off", Username: "26010002", IsActive: false, TenantID: 9},
"u-home": {ID: "u-home", Username: "26010003", IsActive: true, TenantID: 2},
// u-ghost 不在用户表(账号已消失),收编按「平台账号不存在」跳过。
}}
members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{
// u-in 是本空间活跃成员(唯一收编对象);u-super 是成员但跨空间账号
// 不自动收编;u-off 成员关系已停用。
"u-in": {UserID: "u-in", TenantID: 2, Status: types.TenantMemberStatusActive},
"u-super": {UserID: "u-super", TenantID: 2, Status: types.TenantMemberStatusActive},
"u-off": {UserID: "u-off", TenantID: 2, Status: types.TenantMemberStatusSuspended},
}}
svc := newAdoptService(org, users, members)
result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{
"u-in", "u-super", "u-out", "u-off", "u-home", "u-ghost",
})
if err != nil {
t.Fatalf("AdoptHomeTenant: %v", err)
}
if result.Adopted != 1 {
t.Fatalf("only u-in should be adopted, got %d (%+v)", result.Adopted, result.Skipped)
}
reasons := map[string]string{}
for _, sk := range result.Skipped {
reasons[sk.UserID] = sk.Reason
}
want := map[string]string{
"u-super": "跨空间账号不自动收编",
"u-out": "非本空间成员,请先邀请或批量导入加入",
// 停用账号在成员关系校验前拦截:账号不可用,收编无意义。
"u-off": "账号已停用",
"u-home": "归属空间已是本空间",
"u-ghost": "平台账号不存在",
}
for id, reason := range want {
if reasons[id] != reason {
t.Fatalf("user %s reason = %q, want %q", id, reasons[id], reason)
}
}
// 仅收编成功者(u-in)触发补建;跳过者不写任何用户行。
if len(org.roster) != 1 || org.roster[0].UserID != "u-in" {
t.Fatalf("roster backfill should only cover adopted users: %+v", org.roster)
}
if len(users.updated) != 1 || users.updated[0].ID != "u-in" {
t.Fatalf("only adopted user should be persisted: %+v", users.updated)
}
}
func TestAdoptHomeTenantGuards(t *testing.T) {
svc := newAdoptService(&fakeAdoptOrgRepo{}, &fakeAdoptUserRepo{}, &fakeAdoptMemberRepo{})
if _, err := svc.AdoptHomeTenant(context.Background(), 0, []string{"u"}); err == nil {
t.Fatal("zero tenant must be rejected")
}
if _, err := svc.AdoptHomeTenant(context.Background(), 2, nil); err == nil {
t.Fatal("empty user list must be rejected")
}
// 依赖未装配(users/members 为 nil)时报错而不是 panic。
noDep := NewOrgCenterService(&fakeAdoptOrgRepo{}, nil, nil, nil)
if _, err := noDep.AdoptHomeTenant(context.Background(), 2, []string{"u"}); err == nil {
t.Fatal("missing deps must error, not panic")
}
}
@@ -52,7 +52,7 @@ func newFakeOrgRepo() *fakeOrgRepo {
func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) { func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
repo := newFakeOrgRepo() repo := newFakeOrgRepo()
svc := NewOrgCenterService(repo) svc := NewOrgCenterService(repo, nil, nil, nil)
employees := []*types.OrgEmployee{ employees := []*types.OrgEmployee{
{UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号 {UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号
{UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号 {UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号
@@ -76,7 +76,7 @@ func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) { func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) {
repo := newFakeOrgRepo() repo := newFakeOrgRepo()
svc := NewOrgCenterService(repo) svc := NewOrgCenterService(repo, nil, nil, nil)
// u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。 // u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。
employees := []*types.OrgEmployee{ employees := []*types.OrgEmployee{
{UserID: "u-qu", DeptID: "d1"}, {UserID: "u-qu", DeptID: "d1"},
+183 -25
View File
@@ -7,6 +7,7 @@ import (
"io" "io"
"mime/multipart" "mime/multipart"
"strings" "strings"
"sync"
"academy/internal/logger" "academy/internal/logger"
"academy/internal/types" "academy/internal/types"
@@ -20,7 +21,9 @@ import (
// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先); // 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先);
// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型; // 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型;
// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化); // 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化);
// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认。 // 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认;
// 5. 确保企业培训「课件/题库」两个系统默认知识库(CASDOOR/OIDC 自动注册
// 用户进「知识库」页默认可见,与培训域共用同一对库)。
// //
// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程; // 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程;
// 且整体幂等——租户下已存在同名入门库时直接跳过。 // 且整体幂等——租户下已存在同名入门库时直接跳过。
@@ -87,6 +90,8 @@ type tenantBootstrapService struct {
kbService interfaces.KnowledgeBaseService kbService interfaces.KnowledgeBaseService
kgService interfaces.KnowledgeService kgService interfaces.KnowledgeService
tenantService interfaces.TenantService tenantService interfaces.TenantService
// ensureMu 串行化惰性自愈的补建段(见 EnsureTenantDefaultKnowledgeBases)。
ensureMu sync.Mutex
} }
// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the // SeedTenantDefaults implements interfaces.TenantBootstrapService. See the
@@ -103,7 +108,11 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
if tenant == nil || tenant.ID == 0 { if tenant == nil || tenant.ID == 0 {
return return
} }
// 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。 // 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。000160 起
// 租户序列已避开 10000(见 migration 000160_tenant_seq_reserve_builtin_host),
// 新环境不会再有真实空间拿到该 id;存量环境若首空间已占住 10000(引导因此
// 被跳过,一个默认库都没有),其默认库由 EnsureTenantDefaultKnowledgeBases
// 惰性自愈补齐——该路径不带本豁免。
if tenant.ID == types.DefaultBuiltinModelTenantID { if tenant.ID == types.DefaultBuiltinModelTenantID {
return return
} }
@@ -124,6 +133,12 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err) logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
return return
} }
// 企业培训(课件)/(题库)系统默认库:按 Source 标记独立幂等确保(与培训域
// ensureTrainingKnowledgeBases 同源),入门库已初始化的空间同样补齐 ——
// CASDOOR/OIDC 自动注册的用户进「知识库」页即可见两个培训默认库。
s.ensureTrainingKnowledgeBases(seedCtx, tenant.ID, kbs)
for _, kb := range kbs { for _, kb := range kbs {
if kb != nil && kb.Name == BootstrapKBName { if kb != nil && kb.Name == BootstrapKBName {
logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID) logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID)
@@ -141,32 +156,13 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
embedID := PickDefaultModelID(models, types.ModelTypeEmbedding) embedID := PickDefaultModelID(models, types.ModelTypeEmbedding)
rerankID := PickDefaultModelID(models, types.ModelTypeRerank) rerankID := PickDefaultModelID(models, types.ModelTypeRerank)
// 1) 默认知识库。模型解析不到就留空——行为与用户手动不选一致。 // 1) 默认知识库 + 欢迎文档(创建时引导与存量空间自愈共用同一实现)。
kb := &types.KnowledgeBase{ // 模型解析不到就留空——行为与用户手动不选一致。
Name: BootstrapKBName, if err := s.seedStarterKB(seedCtx, chatID, embedID); err != nil {
Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。",
Type: types.KnowledgeBaseTypeDocument,
SummaryModelID: chatID,
EmbeddingModelID: embedID,
}
createdKB, err := s.kbService.CreateKnowledgeBase(seedCtx, kb)
if err != nil {
logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: tenant=%d err=%v", tenant.ID, err)
return return
} }
logger.Infof(ctx, "tenant bootstrap: starter KB created: tenant=%d kb=%s", tenant.ID, createdKB.ID)
// 2) 预置欢迎文档(标准上传管道,切片/向量化由后台任务异步完成)。 // 2) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil {
logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: tenant=%d err=%v", tenant.ID, fhErr)
} else if _, upErr := s.kgService.CreateKnowledgeFromFile(seedCtx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil {
logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: tenant=%d kb=%s err=%v",
tenant.ID, createdKB.ID, upErr)
} else {
logger.Infof(ctx, "tenant bootstrap: welcome doc queued: tenant=%d kb=%s", tenant.ID, createdKB.ID)
}
// 3) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
if rerankID != "" { if rerankID != "" {
if tenant.RetrievalConfig == nil { if tenant.RetrievalConfig == nil {
tenant.RetrievalConfig = &types.RetrievalConfig{} tenant.RetrievalConfig = &types.RetrievalConfig{}
@@ -184,6 +180,168 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
} }
} }
// seedStarterKB 创建「新手入门」知识库并预置欢迎文档(标准上传管道,切片/
// 向量化由后台任务异步完成)。创建时引导(SeedTenantDefaults)与存量空间
// 惰性自愈(EnsureTenantDefaultKnowledgeBases)共用同一实现。fail-open:
// 失败仅记日志返回 error,由调用方决定是否中断后续步骤。
func (s *tenantBootstrapService) seedStarterKB(ctx context.Context, chatID, embedID string) error {
kb := &types.KnowledgeBase{
Name: BootstrapKBName,
Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。",
Type: types.KnowledgeBaseTypeDocument,
SummaryModelID: chatID,
EmbeddingModelID: embedID,
}
createdKB, err := s.kbService.CreateKnowledgeBase(ctx, kb)
if err != nil {
logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: err=%v", err)
return err
}
logger.Infof(ctx, "tenant bootstrap: starter KB created: kb=%s", createdKB.ID)
if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil {
logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: kb=%s err=%v", createdKB.ID, fhErr)
} else if _, upErr := s.kgService.CreateKnowledgeFromFile(ctx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil {
logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: kb=%s err=%v", createdKB.ID, upErr)
} else {
logger.Infof(ctx, "tenant bootstrap: welcome doc queued: kb=%s", createdKB.ID)
}
return nil
}
// EnsureTenantDefaultKnowledgeBases implements interfaces.TenantBootstrapService.
// 存量空间默认库惰性自愈:注册/建空间引导是一次性动作,历史空间会因引导
// 当时的失败(如模型尚未就绪)或保留租户 id 碰撞(migration 000160 前首空间
// 占住 10000 被豁免)而缺失默认库。知识库列表访问时幂等补齐:
// - 企业培训「课件/题库」两库恒补(Source 标记去重);
// - 「新手入门」仅空间为空时补建——零库说明引导从未成功;用户已在使用的
// 空间不复活其主动删除的入门库。
//
// 必须幂等且 fail-open:挂在列表读路径上,任何失败只记日志,不影响正常返回。
func (s *tenantBootstrapService) EnsureTenantDefaultKnowledgeBases(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
logger.Errorf(ctx, "tenant bootstrap: lazy ensure recovered from panic: %v", r)
}
}()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok || tenantID == 0 || s.kbService == nil {
return
}
// 快路径:三项默认库齐备直接返回(一次只读列表,绝大多数请求止于此)。
kbs, err := s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
return
}
if tenantDefaultsComplete(kbs) {
return
}
// 进程内串行化:并发的列表请求只允许一个进入补建段,防止同名默认库
// 重复建档(CreateKnowledgeBase 无名称唯一约束)。锁内复查双保险。
s.ensureMu.Lock()
defer s.ensureMu.Unlock()
kbs, err = s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
return
}
if tenantDefaultsComplete(kbs) {
return
}
// 自愈上下文:执行租户落到目标空间;补建人取当前登录用户(与引导同口径,
// 合成 API-key 用户跳过);CreateKnowledgeFromFile 依赖 TenantInfo。
seedCtx := types.WithExecutionTenant(ctx, tenantID)
if tenant, tErr := s.tenantService.GetTenantByID(ctx, tenantID); tErr == nil && tenant != nil {
seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant)
}
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, uid)
}
logger.Infof(seedCtx, "tenant bootstrap: lazy ensure defaults, tenant=%d existing_kbs=%d", tenantID, len(kbs))
// 培训两库恒补;「新手入门」仅零库空间补建(见方法注释)。
s.ensureTrainingKnowledgeBases(seedCtx, tenantID, kbs)
if len(kbs) == 0 {
models, mErr := s.modelService.ListModels(seedCtx)
if mErr != nil {
logger.Warnf(seedCtx, "tenant bootstrap: lazy ensure list models failed: tenant=%d err=%v", tenantID, mErr)
return
}
_ = s.seedStarterKB(seedCtx,
PickDefaultModelID(models, types.ModelTypeKnowledgeQA),
PickDefaultModelID(models, types.ModelTypeEmbedding))
}
}
// tenantDefaultsComplete 判断空间的开箱默认库是否齐备:新手入门 + 培训课件 +
// 培训题库三项都在才算完整。
func tenantDefaultsComplete(kbs []*types.KnowledgeBase) bool {
var hasStarter, hasCourseware, hasBank bool
for _, kb := range kbs {
if kb == nil {
continue
}
switch {
case kb.Name == BootstrapKBName:
hasStarter = true
case kb.Source == types.KnowledgeBaseSourceTrainingCourseware:
hasCourseware = true
case kb.Source == types.KnowledgeBaseSourceTrainingQuestionBank:
hasBank = true
}
}
return hasStarter && hasCourseware && hasBank
}
// ensureTrainingKnowledgeBases 确保「企业培训(课件)/(题库)」两个系统默认库
// 存在(按 Source 标记去重,缺失即建,已存在跳过;模型由 CreateKnowledgeBase
// 的默认兜底自动绑定)。与培训域 trainingService.ensureTrainingKnowledgeBases
// 完全同源:后续培训上传/题库导入按同一 Source 标记复用这里的库,不会重复建档。
// fail-open:单库失败仅记日志,不阻断注册/建租户主流程。
func (s *tenantBootstrapService) ensureTrainingKnowledgeBases(ctx context.Context, tenantID uint64, existing []*types.KnowledgeBase) {
if s.kbService == nil {
return
}
hasSource := func(source string) bool {
for _, kb := range existing {
if kb != nil && kb.Source == source {
return true
}
}
return false
}
seeds := []struct {
source string
name string
description string
}{
{types.KnowledgeBaseSourceTrainingCourseware, trainingCoursewareKBName, trainingCoursewareKBDescription},
{types.KnowledgeBaseSourceTrainingQuestionBank, trainingQuestionBankKBName, trainingQuestionBankKBDescription},
}
for _, seed := range seeds {
if hasSource(seed.source) {
continue
}
created, err := s.kbService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
Name: seed.name,
Description: seed.description,
Source: seed.source,
})
if err != nil {
logger.Warnf(ctx, "tenant bootstrap: ensure training KB failed: tenant=%d source=%s err=%v",
tenantID, seed.source, err)
continue
}
logger.Infof(ctx, "tenant bootstrap: training KB ensured: tenant=%d kb=%s source=%s",
tenantID, created.ID, seed.source)
}
}
// PickDefaultModelID returns the tenant-visible default model of the given // PickDefaultModelID returns the tenant-visible default model of the given
// type: the is_default row first, then the first active row. Empty string // type: the is_default row first, then the first active row. Empty string
// when the deployment has no usable model of that type. Shared by the // when the deployment has no usable model of that type. Shared by the
@@ -79,6 +79,7 @@ type tenantMemberService struct {
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers
tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal
org interfaces.OrgCenterService // optional; 成员加入时自动入册组织架构(见 ensureOrgRoster)
} }
// NewTenantMemberService constructs the service. Wired up via the DI // NewTenantMemberService constructs the service. Wired up via the DI
@@ -100,12 +101,28 @@ func NewTenantMemberService(
audit interfaces.AuditLogService, audit interfaces.AuditLogService,
userRepo interfaces.UserRepository, userRepo interfaces.UserRepository,
tokenRepo interfaces.AuthTokenRepository, tokenRepo interfaces.AuthTokenRepository,
org interfaces.OrgCenterService,
) interfaces.TenantMemberService { ) interfaces.TenantMemberService {
return &tenantMemberService{ return &tenantMemberService{
repo: repo, repo: repo,
audit: audit, audit: audit,
userRepo: userRepo, userRepo: userRepo,
tokenRepo: tokenRepo, tokenRepo: tokenRepo,
org: org,
}
}
// ensureOrgRoster 成员加入空间后自动补建组织架构员工档案(fail-open)。
// 需求:平台新增成员自动添加到「组织架构」并按同步部门(dept_code/dept_name)
// 自动匹配;对已是成员的用户同样触发(存量自愈),重复调用由
// InsertEmployeesIfAbsent 的仅补空 upsert 幂等兜底,人工维护字段不受影响。
func (s *tenantMemberService) ensureOrgRoster(ctx context.Context, userID string, tenantID uint64) {
if s.org == nil || userID == "" || tenantID == 0 {
return
}
if err := s.org.EnsureEmployeesForUsers(ctx, tenantID, []string{userID}); err != nil {
logger.Warnf(ctx, "[OrgCenter] auto-roster failed (member join continues): user=%s tenant=%d err=%v",
userID, tenantID, err)
} }
} }
@@ -171,6 +188,8 @@ func (s *tenantMemberService) AddMember(
return nil, err return nil, err
} }
if existing != nil { if existing != nil {
// 已是成员:仍补一次入册(存量成员档案缺失时的自愈口)。
s.ensureOrgRoster(ctx, userID, tenantID)
return nil, ErrMembershipAlreadyExists return nil, ErrMembershipAlreadyExists
} }
member := &types.TenantMember{ member := &types.TenantMember{
@@ -201,6 +220,8 @@ func (s *tenantMemberService) AddMember(
TargetUserID: userID, TargetUserID: userID,
Outcome: types.AuditOutcomeSuccess, Outcome: types.AuditOutcomeSuccess,
}) })
// 成员关系落库后自动入册组织架构(新增成员自动添加到名册并匹配部门)。
s.ensureOrgRoster(ctx, userID, tenantID)
return member, nil return member, nil
} }
@@ -218,6 +239,7 @@ func (s *tenantMemberService) EnsureOwner(
return nil, err return nil, err
} }
if existing != nil { if existing != nil {
s.ensureOrgRoster(ctx, userID, tenantID)
return existing, nil return existing, nil
} }
member := &types.TenantMember{ member := &types.TenantMember{
@@ -239,12 +261,15 @@ func (s *tenantMemberService) EnsureOwner(
logger.Infof(ctx, logger.Infof(ctx,
"EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)", "EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)",
userID, tenantID, winner.Role) userID, tenantID, winner.Role)
s.ensureOrgRoster(ctx, userID, tenantID)
return winner, nil return winner, nil
} }
} }
return nil, err return nil, err
} }
logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID) logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID)
// 注册建空间的 Owner 同样自动入册(个人空间名册含创建者本人)。
s.ensureOrgRoster(ctx, userID, tenantID)
return member, nil return member, nil
} }
@@ -215,7 +215,7 @@ func newSyncService(
AdminOrganization: "built-in", AdminOrganization: "built-in",
EmailFallbackDomain: "casdoor.local", EmailFallbackDomain: "casdoor.local",
}} }}
orgSvc := NewOrgCenterService(orgRepo) orgSvc := NewOrgCenterService(orgRepo, nil, nil, nil)
return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc) return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc)
} }
@@ -401,7 +401,7 @@ func TestSyncCasdoorGrantNotSupported(t *testing.T) {
AdminOrganization: "built-in", AdminOrganization: "built-in",
}} }}
// ClientID 为空 → client.Enabled() 为 false → 配置提示路径。 // ClientID 为空 → client.Enabled() 为 false → 配置提示路径。
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
_, err := svc.SyncMembers(context.Background(), 7, "op-1") _, err := svc.SyncMembers(context.Background(), 7, "op-1")
if err == nil || !strings.Contains(err.Error(), "未启用") { if err == nil || !strings.Contains(err.Error(), "未启用") {
t.Fatalf("disabled config should surface actionable error, got: %v", err) t.Fatalf("disabled config should surface actionable error, got: %v", err)
@@ -431,7 +431,7 @@ func TestSyncCasdoorPasswordMode(t *testing.T) {
AdminPassword: "secret-pwd", AdminPassword: "secret-pwd",
EmailFallbackDomain: "casdoor.local", EmailFallbackDomain: "casdoor.local",
}} }}
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
res, err := svc.SyncMembers(context.Background(), 7, "op-1") res, err := svc.SyncMembers(context.Background(), 7, "op-1")
if err != nil { if err != nil {
@@ -465,7 +465,7 @@ func TestSyncCasdoorWrappedPayload(t *testing.T) {
AdminPassword: "secret-pwd", AdminPassword: "secret-pwd",
EmailFallbackDomain: "casdoor.local", EmailFallbackDomain: "casdoor.local",
}} }}
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
res, err := svc.SyncMembers(context.Background(), 7, "op-1") res, err := svc.SyncMembers(context.Background(), 7, "op-1")
if err != nil { if err != nil {
t.Fatalf("SyncMembers(wrapped): %v", err) t.Fatalf("SyncMembers(wrapped): %v", err)
@@ -272,7 +272,7 @@ func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo
// tests pre-date PR 6 and exercise membership invariants only. The // tests pre-date PR 6 and exercise membership invariants only. The
// service's audit and RemoveMember-cleanup hooks are nil-safe, so // service's audit and RemoveMember-cleanup hooks are nil-safe, so
// passing nil keeps existing coverage intact without forcing stubs. // passing nil keeps existing coverage intact without forcing stubs.
return NewTenantMemberService(r, nil, nil, nil), r return NewTenantMemberService(r, nil, nil, nil, nil), r
} }
// cleanupUserRepo is a minimal UserRepository used to assert that // cleanupUserRepo is a minimal UserRepository used to assert that
@@ -359,7 +359,7 @@ func TestTenantMemberService_RemoveMember_ClearsStaleHomeAndRevokesTokens(t *tes
}, },
}} }}
tokenRepo := &cleanupTokenRepo{} tokenRepo := &cleanupTokenRepo{}
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo) svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
ctx := context.Background() ctx := context.Background()
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil { if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
@@ -396,7 +396,7 @@ func TestTenantMemberService_RemoveMember_RevokesTokensEvenWhenHomeUnchanged(t *
"contrib": {ID: "contrib", TenantID: 1}, "contrib": {ID: "contrib", TenantID: 1},
}} }}
tokenRepo := &cleanupTokenRepo{} tokenRepo := &cleanupTokenRepo{}
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo) svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
ctx := context.Background() ctx := context.Background()
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil { if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
+101 -6
View File
@@ -38,11 +38,16 @@ type trainingService struct {
chunkSvc interfaces.ChunkService chunkSvc interfaces.ChunkService
// db 供 OA 企微 userid 同步直查 org_employees(见 training_scheduler 之外的 oa 集成)。 // db 供 OA 企微 userid 同步直查 org_employees(见 training_scheduler 之外的 oa 集成)。
db *gorm.DB db *gorm.DB
// users 平台用户服务:企微扫码免登以绑定身份签发平台 JWT(签到即自动登录,
// 2026-11 需求,见 training_wecom_oauth.go)。
users interfaces.UserService
// wecomOAuth 企微网页授权后端(容器注入 wecompush 适配,本层不引 internal/im)。
wecomOAuth WecomOAuthBackend
} }
// NewTrainingService constructs the production training service. // NewTrainingService constructs the production training service.
func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces.KnowledgeBaseService, knowledgeSvc interfaces.KnowledgeService, org interfaces.OrgCenterService, fileSvc interfaces.FileService, models interfaces.ModelService, chunkSvc interfaces.ChunkService, db *gorm.DB) interfaces.TrainingService { func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces.KnowledgeBaseService, knowledgeSvc interfaces.KnowledgeService, org interfaces.OrgCenterService, fileSvc interfaces.FileService, models interfaces.ModelService, chunkSvc interfaces.ChunkService, db *gorm.DB, users interfaces.UserService, wecomOAuth WecomOAuthBackend) interfaces.TrainingService {
return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db} return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db, users: users, wecomOAuth: wecomOAuth}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -291,6 +296,25 @@ func (s *trainingService) CurrentMember(ctx context.Context, tenantID uint64, us
}, nil }, nil
} }
// ResolveTrainingTenant 企业培训数据空间解析(000160):培训域不再绑定单一工作区
// —— 同一组织的人员只要员工档案(org_employees)里存在,无论当前在哪个工作区,
// 都按其档案所在空间参与培训、课程发布与学习。优先级:
// 1. 当前空间已有培训档案 → 当前空间(多档案用户显式切换工作区的语义优先);
// 2. 否则跨空间取最早在职档案所在空间;
// 3. 都没有 → 维持当前空间(默认学员口径,行为与升级前一致)。
func (s *trainingService) ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error) {
if userID == "" || activeTenantID == 0 {
return activeTenantID, nil
}
if _, err := s.repo.GetMemberByUserID(ctx, activeTenantID, userID); err == nil {
return activeTenantID, nil
}
if tenantID, err := s.repo.FindArchiveTenantID(ctx, userID); err == nil && tenantID != 0 {
return tenantID, nil
}
return activeTenantID, nil
}
// trainingMemberWithRoles 填充员工档案的培训模块绑定角色展示字段。 // trainingMemberWithRoles 填充员工档案的培训模块绑定角色展示字段。
func (s *trainingService) trainingMemberWithRoles(ctx context.Context, tenantID uint64, member *types.TrainingMember) (*types.TrainingMember, error) { func (s *trainingService) trainingMemberWithRoles(ctx context.Context, tenantID uint64, member *types.TrainingMember) (*types.TrainingMember, error) {
binding, err := s.org.GetModuleMember(ctx, tenantID, types.OrgModuleTraining, member.ID) binding, err := s.org.GetModuleMember(ctx, tenantID, types.OrgModuleTraining, member.ID)
@@ -372,6 +396,8 @@ func (s *trainingService) EnsureLecturerRole(ctx context.Context, tenantID uint6
// SaveDemand creates or updates one demand with rule-based field checking. // SaveDemand creates or updates one demand with rule-based field checking.
// 已确认的需求不再允许编辑(先由人事回退)。 // 已确认的需求不再允许编辑(先由人事回退)。
func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) { func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) {
// 编辑场景的存量值(课程关联保留口径,见下方课程校验)。
var prevLibraryCourseID, prevCourseName string
if demand.CourseName == "" { if demand.CourseName == "" {
return nil, errors.NewBadRequestError("课程名称不能为空") return nil, errors.NewBadRequestError("课程名称不能为空")
} }
@@ -393,6 +419,10 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
if existing.Status == types.TrainingDemandConfirmed { if existing.Status == types.TrainingDemandConfirmed {
return nil, errors.NewBadRequestError("已确认的需求不可编辑") return nil, errors.NewBadRequestError("已确认的需求不可编辑")
} }
// 编辑保留原课程关联(000158):课程名未变时跳过重匹配,匹配失败时不
// 清空已有关联(UpdateDemand 全量更新,零值会误清)。
prevLibraryCourseID = existing.LibraryCourseID
prevCourseName = existing.CourseName
} }
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。 // 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。 // 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
@@ -413,6 +443,33 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
demand.Status = types.TrainingDemandSubmitted demand.Status = types.TrainingDemandSubmitted
} }
// 课程校验(000158):按课程名称在课程管理精准查找,命中自动匹配该课程;
// 未命中自动新增该课程(待核验,归属需求部门)。匹配/建档失败为硬失败:
// 整个保存随之中止并向前端透出原因(不静默跳过,避免"需求存了但课程没建"
// 的隐性不一致)。课程名未变且已有关联时跳过重匹配(编辑保留原关联)。
// 外部讲师口径已在上方互斥清空,这里原样透传即可。
switch {
case prevLibraryCourseID != "" && prevCourseName == demand.CourseName:
demand.LibraryCourseID = prevLibraryCourseID
case strings.TrimSpace(demand.CourseName) != "":
proto := &types.TrainingCourseLibrary{
Name: demand.CourseName,
OwnerDeptID: demand.DeptID,
Category: demand.Category,
SuitableMembers: demand.PostScope,
LecturerID: demand.LecturerID,
LecturerExternal: demand.LecturerExternal,
}
id, _, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, demand.SubmitterID)
if err != nil {
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, demand.CourseName, err)
return nil, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
}
demand.LibraryCourseID = id
default:
demand.LibraryCourseID = prevLibraryCourseID
}
if demand.ID == "" { if demand.ID == "" {
demand.ID = trainingNewID() demand.ID = trainingNewID()
demand.TenantID = tenantID demand.TenantID = tenantID
@@ -431,10 +488,14 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
} }
// ImportDemands batch-imports demands (调研表在线化/邮件替代)。 // ImportDemands batch-imports demands (调研表在线化/邮件替代)。
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error) { // 返回导入行与自动新增的待核验课程数(000158)。
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error) {
if len(demands) == 0 { if len(demands) == 0 {
return nil, errors.NewBadRequestError("导入数据为空") return nil, 0, errors.NewBadRequestError("导入数据为空")
} }
// 课程校验批内去重(000158):同名行只查/建一次,其余行复用条目 id。
courseCache := map[string]string{}
coursesCreated := 0
for i := range demands { for i := range demands {
demands[i].ID = trainingNewID() demands[i].ID = trainingNewID()
demands[i].TenantID = tenantID demands[i].TenantID = tenantID
@@ -450,17 +511,51 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。 // 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。 // 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。 // 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
// 讲师口径互斥与 SaveDemand 一致:系统员工优先,外部姓名仅在无 id 时生效。
if demands[i].LecturerID != "" {
demands[i].LecturerExternal = ""
}
msgs := []string{} msgs := []string{}
if demands[i].DeptID == "" { if demands[i].DeptID == "" {
msgs = append(msgs, "未指定部门") msgs = append(msgs, "未指定部门")
} }
demands[i].CheckMsg = strings.Join(msgs, ";") demands[i].CheckMsg = strings.Join(msgs, ";")
demands[i].CheckStatus = types.TrainingCheckPending demands[i].CheckStatus = types.TrainingCheckPending
// 课程校验(000158):按名称精准查找自动匹配,未命中自动新增(待核验)。
// 硬失败同 SaveDemand:任一行匹配/建档失败整批中止并透出原因;
// 批内同名复用首个条目,不重复建档。
name := strings.TrimSpace(demands[i].CourseName)
if name == "" {
continue
}
if id, ok := courseCache[name]; ok {
demands[i].LibraryCourseID = id
continue
}
proto := &types.TrainingCourseLibrary{
Name: name,
OwnerDeptID: demands[i].DeptID,
Category: demands[i].Category,
SuitableMembers: demands[i].PostScope,
LecturerID: demands[i].LecturerID,
LecturerExternal: demands[i].LecturerExternal,
}
id, created, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, updaterID)
if err != nil {
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, name, err)
return nil, 0, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
}
courseCache[name] = id
demands[i].LibraryCourseID = id
if created {
coursesCreated++
}
} }
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil { if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
return nil, err return nil, 0, err
} }
return demands, nil return demands, coursesCreated, nil
} }
// ConfirmDemand marks one demand confirmed and auto-aggregates it into the // ConfirmDemand marks one demand confirmed and auto-aggregates it into the
+328 -27
View File
@@ -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,13 +159,19 @@ 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
} }
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153): // applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/ // 课程名称/类型随课程管理主数据锁定;形式(mode)为计划侧独立字段——计划形式
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。 // 指本次培训线上办还是线下办,与课程主数据的线上课/线下课口径不同,不随课程
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。 // 带出,由创建/调整表单自行选择;讲师 000161 起计划侧可改(更新路径不再覆盖,
// 改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时讲师/学时/
// 课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存
// (fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary { func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
if course.LibraryCourseID == "" { if course.LibraryCourseID == "" {
return nil return nil
@@ -142,11 +181,11 @@ 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) logger.Error(ctx, "Failed to load library course for plan binding", err, "library_course_id", course.LibraryCourseID)
return nil return nil
} }
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖。 // 锁定字段:随课程管理主数据,请求侧取值一律覆盖(形式除外,见上)。
course.Name = item.Name course.Name = item.Name
course.Type = item.Type course.Type = item.Type
course.Mode = item.Mode if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") {
if item.LecturerID != "" || item.LecturerExternal != "" { // 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。
course.LecturerID = item.LecturerID course.LecturerID = item.LecturerID
course.LecturerExternal = item.LecturerExternal course.LecturerExternal = item.LecturerExternal
} }
@@ -158,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 != "" {
@@ -172,6 +217,35 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
return item return item
} }
// syncPlanLecturerToLibrary 计划侧讲师改动回写课程管理主数据(000161):
// 讲师(系统员工 id/外部姓名)与课程管理条目不一致时经 SaveCourseLibraryItem
// 回写——其编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须由
// 所属部门课长/经理重新签核。fail-open:回写失败记日志不阻断计划保存。
func (s *trainingService) syncPlanLecturerToLibrary(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, course *types.TrainingCourse, updaterID string) {
if item == nil || course == nil {
return
}
lecturerID, lecturerExt := strings.TrimSpace(course.LecturerID), strings.TrimSpace(course.LecturerExternal)
if lecturerID != "" {
lecturerExt = ""
}
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
return
}
updated := *item
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
if _, err := s.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync plan lecturer to course library", err, "library_course_id", item.ID)
return
}
logger.Infof(ctx, "[Training] plan lecturer synced to library (verify reset), tenant=%d course=%s operator=%s", tenantID, item.Code, updaterID)
// 讲师自动补齐 lecturer 角色绑定(讲师名册/下拉可见,fail-open)。
if err := s.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role on plan sync", err)
}
}
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时): // attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件 // 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。 // 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
@@ -232,8 +306,8 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
return course, nil return course, nil
} }
course.TenantID = tenantID course.TenantID = tenantID
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。 // 课程管理关联存在时锁定带出字段(000153;讲师 000161 起计划侧可改)。
s.applyLibraryCourseBinding(ctx, tenantID, course, false) libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, false)
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。 // 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
old, err := s.repo.GetCourse(ctx, tenantID, course.ID) old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
if err != nil { if err != nil {
@@ -242,6 +316,10 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
if err := s.repo.UpdateCourse(ctx, course); err != nil { if err := s.repo.UpdateCourse(ctx, course); err != nil {
return nil, err return nil, err
} }
// 计划侧讲师改动回写课程管理并重置待核验(000161):发布前须重新签核。
if old == nil || old.LecturerID != course.LecturerID || old.LecturerExternal != course.LecturerExternal {
s.syncPlanLecturerToLibrary(ctx, tenantID, libItem, course, updaterID)
}
if old != nil { if old != nil {
s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID) s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID)
} }
@@ -358,15 +436,68 @@ func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id
if course.Status == types.TrainingCoursePublished { if course.Status == types.TrainingCoursePublished {
return course, nil return course, nil
} }
// 关联课程管理条目须已核验确认(000157):月培训计划发布/保存并发布共用本端点, // 发布必填校验(000161):课程(须关联课程管理且已签核)、参加人员;
// 未核验的课程拦截并友好提示,核验入口在「课程管理」。 // 线下计划另需授课时间/授课地点/讲师(线上计划豁免这三项)。
if course.LibraryCourseID != "" { if strings.TrimSpace(course.LibraryCourseID) == "" {
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID) return nil, errors.NewBadRequestError("发布前需先关联课程管理课程")
if libErr != nil || lib == nil { }
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程") lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if libErr != nil || lib == nil {
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程")
}
// 课程须已完成签核(000157/000158):未核验(待核验)时按统一文案拦截,核验入口在「课程管理」。
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed {
return nil, errors.NewBadRequestError("请联系课长或经理审核课程!").
WithDetails(fmt.Sprintf("课程《%s》尚未完成签核,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name))
}
// 线上计划课件校验(原 handler 前置,收口到 service 统一口径):计划自带课件
// 或关联课程的课程管理课件(名称登记/文件/知识库文档,000156 随课程带出)
// 任一有值即可;考题非必填,不参与发布校验。
if course.Mode == types.TrainingCourseModeOnline {
materials, matErr := s.repo.ListMaterials(ctx, tenantID, course.ID)
if matErr != nil {
return nil, matErr
} }
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed { hasLibCourseware := strings.TrimSpace(lib.MaterialName) != "" ||
return nil, errors.NewBadRequestError(fmt.Sprintf("关联课程《%s》尚未核验确认,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name)) strings.TrimSpace(lib.FileKey) != "" ||
strings.TrimSpace(lib.KnowledgeID) != ""
if len(materials) == 0 && !hasLibCourseware {
return nil, errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)")
}
}
// 参加人员:适用人员非空或场次学员名单有人(跨场次)任一满足即可。
if strings.TrimSpace(course.PostScope) == "" {
enrolled, enrolledErr := s.repo.CountEnrolledMembersByCourseID(ctx, tenantID, course.ID)
if enrolledErr != nil {
return nil, enrolledErr
}
if enrolled == 0 {
return nil, errors.NewBadRequestError("发布前需先设置参加人员")
}
}
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) == "" {
return nil, errors.NewBadRequestError("发布前需先设置授课时间")
}
if strings.TrimSpace(course.Location) == "" {
return nil, errors.NewBadRequestError("发布前需先设置授课地点")
}
if strings.TrimSpace(course.LecturerID) == "" && strings.TrimSpace(course.LecturerExternal) == "" {
return nil, errors.NewBadRequestError("发布前需先指定讲师")
} }
} }
course.Status = types.TrainingCoursePublished course.Status = types.TrainingCoursePublished
@@ -578,8 +709,40 @@ func (s *trainingService) CreateMaterial(ctx context.Context, tenantID uint64, m
} }
// ListMaterials returns course materials. // ListMaterials returns course materials.
// 计划未自带课件时回退关联课程的课程管理课件(000156 随课程带出,发布校验同口径):
// 以课程管理条目 id 作为虚拟课件 id 返回,学习详情页预览/文件流/进度上报同链路可用
// (GetMaterialFile 对虚拟 id 回退课程管理文件流);仅登记名称而无文件/知识库文档时
// 不合成(无内容可打开)。
func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) { func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) {
return s.repo.ListMaterials(ctx, tenantID, courseID) items, err := s.repo.ListMaterials(ctx, tenantID, courseID)
if err != nil || len(items) > 0 || courseID == "" {
return items, err
}
course, cErr := s.repo.GetCourse(ctx, tenantID, courseID)
if cErr != nil || course == nil || strings.TrimSpace(course.LibraryCourseID) == "" {
return items, nil
}
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if libErr != nil || lib == nil || (lib.KnowledgeID == "" && lib.FileKey == "") {
return items, nil
}
name := strings.TrimSpace(lib.FileName)
if name == "" {
name = strings.TrimSpace(lib.MaterialName)
}
if name == "" {
name = lib.Name
}
return []*types.TrainingMaterial{{
ID: lib.ID,
TenantID: tenantID,
CourseID: courseID,
Kind: "doc",
Name: name,
FileKey: lib.FileKey,
KnowledgeID: lib.KnowledgeID,
Size: lib.FileSize,
}}, nil
} }
// AttachQuestionBank 建课/编辑课时反向关联题库:把 bank.course_id 指向课程, // AttachQuestionBank 建课/编辑课时反向关联题库:把 bank.course_id 指向课程,
@@ -604,6 +767,8 @@ func (s *trainingService) AttachQuestionBank(ctx context.Context, tenantID uint6
// CreateSignCode generates (or refreshes) the session's sign-in code with an // CreateSignCode generates (or refreshes) the session's sign-in code with an
// optional geo-fence; default expiry = start + 4h or now + 12h. // optional geo-fence; default expiry = start + 4h or now + 12h.
// 2026-11 轮换需求:每轮 token 有效期 = min(now + rotation_sec, 场次总有效期),
// 讲师页轮询 GetSignCode 惰性续轮。
func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error) { func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, sessionID) session, err := s.repo.GetSession(ctx, tenantID, sessionID)
if err != nil { if err != nil {
@@ -612,12 +777,19 @@ func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, s
if radius <= 0 { 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))
} }
expire := time.Now().Add(12 * time.Hour) now := time.Now()
expire := now.Add(12 * time.Hour)
if session.StartAt != nil { if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(time.Now()) { if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
expire = candidate expire = candidate
} }
} }
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation > 0 {
if capped := now.Add(rotation); capped.Before(expire) {
expire = capped
}
}
code := &types.TrainingSignCode{ code := &types.TrainingSignCode{
ID: trainingNewID(), ID: trainingNewID(),
TenantID: tenantID, TenantID: tenantID,
@@ -640,22 +812,86 @@ func trainingNewToken() string {
return strings.ReplaceAll(trainingNewID(), "-", "")[:32] return strings.ReplaceAll(trainingNewID(), "-", "")[:32]
} }
// GetSignCode returns the session's active sign-in code. // GetSignCode returns the session's active sign-in code. 超过轮换窗口
// (rotation_sec,默认 5 分钟)时惰性轮换:旧 token 挪入 prev(宽限期内仍可
// 签到),新码即时生效 —— 讲师页每 10s 轮询本接口即可驱动自动更新。
func (s *trainingService) GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) { func (s *trainingService) GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeBySession(ctx, tenantID, sessionID) code, err := s.repo.GetSignCodeBySession(ctx, tenantID, sessionID)
if err != nil { if err != nil {
return nil, errors.NewNotFoundError("尚未生成签到码") return nil, errors.NewNotFoundError("尚未生成签到码")
} }
return code, nil rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation <= 0 || time.Now().Before(code.UpdatedAt.Add(rotation)) {
return code, nil
}
return s.rotateSignCode(ctx, tenantID, code)
}
// rotateSignCode 轮换场次签到码:生成新 token,旧 token/有效期挪入 prev 供
// 宽限签到(rotation_grace_sec,默认 30s,0 = 严格作废);upsert 覆盖唯一行后
// 旧 token 即刻退出当前码位(GetSignCodeByToken 不再命中,自然作废)。
// 新码有效期 = min(now + rotation_sec, 场次总有效期):后者沿用开课 +4h /
// 兜底 +12h 的既有口径,超期后不再续轮,交由现有过期校验拦截。
func (s *trainingService) rotateSignCode(ctx context.Context, tenantID uint64, code *types.TrainingSignCode) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, code.SessionID)
if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
now := time.Now()
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
expire := now.Add(rotation)
overall := now.Add(12 * time.Hour)
if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
overall = candidate
}
}
if expire.After(overall) {
expire = overall
}
next := &types.TrainingSignCode{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: code.SessionID,
Token: trainingNewToken(),
ExpireAt: &expire,
PrevToken: code.Token,
PrevExpireAt: code.ExpireAt,
GeoLat: code.GeoLat,
GeoLng: code.GeoLng,
GeoRadius: code.GeoRadius,
CreatedBy: code.CreatedBy,
}
if err := s.repo.UpsertSignCode(ctx, next); err != nil {
return nil, err
}
return next, nil
} }
// Checkin performs the scan sign-in with rule-based anti-fraud checks: // Checkin performs the scan sign-in with rule-based anti-fraud checks:
// token/expiry, roster membership, duplicate scan, late arrival, geo fence. // token/expiry, same-day, roster membership, employee-no match, nonce replay,
// duplicate scan, late arrival, geo fence.
// 一期为确定性规则引擎,不调 LLM;规则参数来自 sign_policy 配置。 // 一期为确定性规则引擎,不调 LLM;规则参数来自 sign_policy 配置。
func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID, token string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) { // 2026-11 企微扫码需求增强:
// - 培训当天校验:非当天扫码签到直接友好提示(提前扫/过期补扫分文案);
// - 工号严格校验(in.EmployeeNo 非空时):须与登录账号档案工号一致,且必须在
// 该场次「参加人员」名单中 —— 名单外直接拒绝(不再仅标记待复核);
// - nonce 防重放 + client_ts 时钟偏差校验;
// - 轮换宽限:token 未命中当前码时接受 prev_token 在宽限期内签到。
// 既有登录态签到(不带 employee_no/nonce)行为不变:名单外仍标记 not_in_roster
// 进待复核,不硬拒。
func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID string, in *types.CheckinInput) (*types.TrainingSignRecord, error) {
if in == nil || in.Token == "" {
return nil, errors.NewBadRequestError("签到码无效")
}
token, lat, lng := in.Token, in.Lat, in.Lng
code, err := s.repo.GetSignCodeByToken(ctx, tenantID, token) code, err := s.repo.GetSignCodeByToken(ctx, tenantID, token)
if err != nil { if err != nil {
return nil, errors.NewBadRequestError("签到码无效") // 轮换宽限:未命中当前码时尝试前码(prev_token),宽限期内放行。
code, err = s.resolveCheckinPrevToken(ctx, tenantID, token)
if err != nil {
return nil, errors.NewBadRequestError("签到码无效或已更新,请重新扫码")
}
} }
if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) { if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) {
return nil, errors.NewBadRequestError("签到码已过期") return nil, errors.NewBadRequestError("签到码已过期")
@@ -672,7 +908,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return nil, errors.NewForbiddenError("未建立培训档案,无法签到") return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
} }
// 名单校验(名单外人员自动标记)。 // 名单校验(名单外人员自动标记;严格模式下直接拒绝,见下)。
roster, err := s.repo.ListEnrollments(ctx, tenantID, session.ID) roster, err := s.repo.ListEnrollments(ctx, tenantID, session.ID)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -686,6 +922,47 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
} }
now := time.Now() now := time.Now()
// 严格扫码链路(employee_no 非空,即 2026-11 新签到页):当天校验/工号+名单
// 硬拒/nonce 防重放/时钟偏差仅作用于此链路。既有路径(登录态直签、代录补签)
// 行为不变 —— 尤其代录补签常发生在非当天,当天校验不得拦截。
strictScan := strings.TrimSpace(in.EmployeeNo) != ""
// 培训当天校验(2026-11 需求规则 1):非当天扫码签到,分提前/滞后友好提示。
// 时区固定北京时间,与前端 fmtBeijingTime 口径一致。
if strictScan && s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "same_day_check", 1) > 0 &&
session.StartAt != nil && !sameBeijingDay(now, *session.StartAt) {
if session.StartAt.After(now) {
return nil, errors.NewBadRequestError(
"培训尚未开始:该课程 " + fmtBeijingCST(session.StartAt) + " 开课,培训当天再来签到")
}
return nil, errors.NewBadRequestError("本课程签到已结束,无法补签")
}
// 工号严格校验(2026-11 需求规则 2 + 补充规则):工号须与档案一致,且必须在
// 「参加人员」名单中,名单外直接拒绝。
if strictScan {
if !strings.EqualFold(strings.TrimSpace(member.EmployeeNo), strings.TrimSpace(in.EmployeeNo)) {
return nil, errors.NewForbiddenError("录入工号与当前账号的档案工号不一致,请确认后重试")
}
if !inRoster {
return nil, errors.NewForbiddenError("您不在该课程的「参加人员」名单中,请联系讲师或人事确认")
}
}
// nonce 防重放 + 时钟偏差(仅扫码链路携带;同 nonce 二次提交直接拒绝)。
if strictScan && in.Nonce != "" {
if dup, derr := s.repo.GetSignRecordByNonce(ctx, tenantID, in.Nonce); derr == nil && dup != nil {
return nil, errors.NewBadRequestError("签到请求无效,请刷新页面后重试")
}
}
skewSec := s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "clock_skew_sec", 60)
if strictScan && in.ClientTS > 0 && skewSec > 0 {
if diff := now.UnixMilli() - in.ClientTS; diff > int64(skewSec)*1000 || diff < -int64(skewSec)*1000 {
return nil, errors.NewBadRequestError("签到请求时间异常,请校准手机时间后重试")
}
}
flags := []string{} flags := []string{}
status := types.TrainingSignNormal status := types.TrainingSignNormal
@@ -706,7 +983,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
} }
} }
// 名单外人员标记。 // 名单外人员标记(工号严格链路已在上方硬拒,此处仅既有登录态路径可达)。
if !inRoster { if !inRoster {
flags = append(flags, "not_in_roster") flags = append(flags, "not_in_roster")
status = types.TrainingSignAbnormal status = types.TrainingSignAbnormal
@@ -717,6 +994,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return nil, errors.NewBadRequestError("您已签到,请勿重复扫码") return nil, errors.NewBadRequestError("您已签到,请勿重复扫码")
} }
channel := in.Channel
if channel == "" { if channel == "" {
channel = "wecom_scan" channel = "wecom_scan"
} }
@@ -732,6 +1010,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
Lng: lng, Lng: lng,
DistanceM: distance, DistanceM: distance,
Status: status, Status: status,
Nonce: strings.TrimSpace(in.Nonce),
AbnormalFlags: flagsJSON, AbnormalFlags: flagsJSON,
} }
if err := s.repo.UpsertSignRecord(ctx, record); err != nil { if err := s.repo.UpsertSignRecord(ctx, record); err != nil {
@@ -745,6 +1024,28 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
return record, nil return record, nil
} }
// resolveCheckinPrevToken 轮换宽限:当前码未命中时按前码定位,宽限期内放行
// (rotation_grace_sec,默认 30s,0 = 严格作废)。跨租户 token 一律拒绝。
func (s *trainingService) resolveCheckinPrevToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil || code.TenantID != tenantID || code.Token == token {
return nil, errors.NewBadRequestError("签到码无效")
}
grace := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_grace_sec", 30)) * time.Second
if code.PrevExpireAt == nil || time.Now().After(code.PrevExpireAt.Add(grace)) {
return nil, errors.NewBadRequestError("签到码已更新,请重新扫码")
}
return code, nil
}
// fmtBeijingCST 时间格式化为北京时间文案(当天性提示用)。
func fmtBeijingCST(t *time.Time) string {
if t == nil {
return ""
}
return t.In(time.FixedZone("CST", 8*3600)).Format("2006-01-02 15:04")
}
// haversineMeters computes the great-circle distance in meters. // haversineMeters computes the great-circle distance in meters.
func haversineMeters(lat1, lng1, lat2, lng2 float64) float64 { func haversineMeters(lat1, lng1, lat2, lng2 float64) float64 {
const earthRadius = 6371000.0 const earthRadius = 6371000.0
+45 -2
View File
@@ -175,7 +175,33 @@ 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
}
// 试题变更回待核验(000163):同课件「换课件即回待核验」口径,导入后须
// 所属部门课长/经理重新签核,课程方可发布。
s.resetLibraryCourseVerify(ctx, tenantID, created.LibraryCourseID)
return created, nil
}
// resetLibraryCourseVerify 课程管理条目试题变更后重置签核状态(000163):
// 更换/导入题库同课件变更口径回「待核验」。fail-open:条目缺失或回写失败
// 仅记日志,不阻断题库操作本身。
func (s *trainingService) resetLibraryCourseVerify(ctx context.Context, tenantID uint64, libraryCourseID string) {
if libraryCourseID == "" {
return
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, libraryCourseID)
if err != nil || item == nil {
return
}
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
logger.Warnf(ctx, "[Training] reset library course verify failed, tenant=%d course=%s err=%v", tenantID, libraryCourseID, err)
}
} }
// ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。 // ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。
@@ -188,6 +214,7 @@ func (s *trainingService) ListLibraryCourseQuestionBanks(ctx context.Context, te
// LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体 // LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体
// 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。 // 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。
// 更换后重置签核状态(000163):同课件变更口径,须课长/经理重新签核方可发布。
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("缺少课程管理条目")
@@ -195,7 +222,11 @@ func (s *trainingService) LinkQuestionBankToLibraryCourse(ctx context.Context, t
if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil { if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil {
return errors.NewNotFoundError("题库不存在") return errors.NewNotFoundError("题库不存在")
} }
return s.repo.RelinkQuestionBankToLibraryCourse(ctx, tenantID, libraryCourseID, bankID) if err := s.repo.RelinkQuestionBankToLibraryCourse(ctx, tenantID, libraryCourseID, bankID); err != nil {
return err
}
s.resetLibraryCourseVerify(ctx, tenantID, libraryCourseID)
return nil
} }
// DeleteQuestionBank 删除题库(连带题目与缓存试卷;试题维护抽屉删除入口,000153)。 // DeleteQuestionBank 删除题库(连带题目与缓存试卷;试题维护抽屉删除入口,000153)。
@@ -1135,6 +1166,18 @@ func (s *trainingService) ListMyLearningTasks(ctx context.Context, tenantID uint
return s.repo.ListLearningTasks(ctx, tenantID, member.ID) return s.repo.ListLearningTasks(ctx, tenantID, member.ID)
} }
// ListMyEnrolledCourseIDs 我经场次学员名单报名的课程 id 去重集合(我的培训
// 「我参加」判定数据源):参加人员此前只落场次名单与 post_scope 文案,不进
// 任何"与我相关"判定,线下课参加人员在「我的培训」看不到课。未建培训档案
// 返回空集(与 ListMyLearningTasks 同口径,不报错)。
func (s *trainingService) ListMyEnrolledCourseIDs(ctx context.Context, tenantID uint64, userID string) ([]string, error) {
member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID)
if err != nil {
return []string{}, nil
}
return s.repo.ListMyEnrolledCourseIDs(ctx, tenantID, member.ID)
}
// ListCourseLearningTasks returns all members' learning tasks of one course // ListCourseLearningTasks returns all members' learning tasks of one course
// (管理端「学习考试」课程学习情况;任务不存在但已发布课程的名单成员由前端按待学习渲染口径,此处按实际任务行返回)。 // (管理端「学习考试」课程学习情况;任务不存在但已发布课程的名单成员由前端按待学习渲染口径,此处按实际任务行返回)。
func (s *trainingService) ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error) { func (s *trainingService) ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error) {
@@ -221,6 +221,11 @@ func trainingKBSummary(kb *types.KnowledgeBase) *types.TrainingKnowledgeBaseSumm
func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64, materialID string) (io.ReadCloser, string, error) { func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64, materialID string) (io.ReadCloser, string, error) {
material, err := s.repo.GetMaterial(ctx, tenantID, materialID) material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
if err != nil { if err != nil {
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
// 材料行不存在时按课程管理条目取文件流(最新课件条目),与发布/学习链路同口径。
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID, ""); libErr == nil {
return rc, fileName, nil
}
return nil, "", werrors.NewNotFoundError("课件不存在") return nil, "", werrors.NewNotFoundError("课件不存在")
} }
if material.KnowledgeID != "" { if material.KnowledgeID != "" {
+262 -57
View File
@@ -2,6 +2,8 @@ package service
import ( import (
"context" "context"
"encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"mime/multipart" "mime/multipart"
@@ -9,6 +11,7 @@ import (
"time" "time"
excelize "github.com/xuri/excelize/v2" excelize "github.com/xuri/excelize/v2"
"gorm.io/gorm"
werrors "academy/internal/errors" werrors "academy/internal/errors"
"academy/internal/logger" "academy/internal/logger"
@@ -53,6 +56,13 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
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"
} }
@@ -62,6 +72,51 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
return nil return nil
} }
// 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)
@@ -107,6 +162,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):前端表单同口径锁定,服务端兜底
// 覆盖,防止绕过前端改部门。创建人无部门档案时保留原值(可为空)。
if member, err := s.CurrentMember(ctx, tenantID, updaterID); err == nil && member != nil && member.DeptID != "" {
item.OwnerDeptID = member.DeptID
}
// 课程编号(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 {
@@ -119,19 +179,17 @@ 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 == "" { // 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
item.KnowledgeID = old.KnowledgeID item.OwnerDeptID = old.OwnerDeptID
} // 编辑即回待审核(000157):内容变更后原审核结论作废,需重新审核。
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
item.VerifyStatus = types.CourseLibraryVerifyPending item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = "" item.ConfirmedBy = ""
item.ConfirmedAt = nil item.ConfirmedAt = nil
@@ -170,7 +228,8 @@ func (s *trainingService) GetCourseLibraryItem(ctx context.Context, tenantID uin
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 / // SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 /
// offline 已下线;培训中心「和信课程」目录仅展示已发布课程。 // offline 已下线;培训中心「和信课程」目录仅展示已发布课程。
// 发布前置校验核验状态(000157):仅「已确认」课程可发布。 // 发布前置校验核验状态(000157):仅「已确认」课程可发布;
// 发布必须有课件(名称登记不算,须已上传课件文件或已挂接知识库课件文档)。
func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error { func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
if status != "published" && status != "offline" { if status != "published" && status != "offline" {
return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)") return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)")
@@ -182,14 +241,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" && !item.HasCourseMaterial() {
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 {
@@ -199,20 +268,88 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
continue // 已确认行幂等跳过 continue // 已确认行幂等跳过
} }
if deptScope != "" && item.OwnerDeptID != deptScope { if deptScope != "" && item.OwnerDeptID != deptScope {
continue // 课长/经理仅可核验本部门课程 continue // 课长/经理仅可审核本部门课程
}
// 课程权限必填(审核前置):权限两列与存量适合人员均未设置时拦截。
if !item.HasPermissionSet() {
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):按课程名称在课程管理精准
// 查找,命中直接复用(自动匹配该课程);未命中自动新增该课程——待核验(000157
// 流转)、草稿、归属需求部门,由所属部门课长/经理核验,发布前必须已签核完成。
// proto 携带需求行带入的名称/部门/讲师/分类/适合人员,其余字段按课程管理默认口径。
// 返回条目 id 与是否新建。查询/建档失败一律返回错误(硬失败,不静默跳过),
// 由需求保存/导入整批回滚并向前端透出真实原因。
func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenantID uint64, proto *types.TrainingCourseLibrary, creatorID string) (string, bool, error) {
name := strings.TrimSpace(proto.Name)
if name == "" {
return "", false, werrors.NewBadRequestError("课程名称不能为空")
}
hit, err := s.repo.FindCourseLibraryByName(ctx, tenantID, name)
switch {
case err == nil && hit != nil:
return hit.ID, false, nil
case !errors.Is(err, gorm.ErrRecordNotFound):
// 查询本身出错(非未命中):不得当作"不存在"去重复建档,直接上抛。
return "", false, err
}
item := &types.TrainingCourseLibrary{
ID: trainingNewID(),
TenantID: tenantID,
Name: name,
Code: s.nextCourseLibraryCode(ctx, tenantID),
OwnerDeptID: proto.OwnerDeptID,
Category: strings.TrimSpace(proto.Category),
SuitableMembers: strings.TrimSpace(proto.SuitableMembers),
LecturerID: proto.LecturerID,
LecturerExternal: strings.TrimSpace(proto.LecturerExternal),
Type: "required",
Mode: types.TrainingCourseModeOffline,
PublishStatus: "draft",
VerifyStatus: types.CourseLibraryVerifyPending,
CreatorID: creatorID,
Materials: types.JSON([]byte("[]")),
}
if item.LecturerID != "" {
item.LecturerExternal = ""
}
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
return "", false, err
}
logger.Infof(ctx, "[Training] demand course auto-created to library, tenant=%d course=%s dept=%s creator=%s", tenantID, item.Code, item.OwnerDeptID, creatorID)
return item.ID, true, nil
} }
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在 // ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
@@ -305,8 +442,11 @@ 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 出题/学习抽屉等既有依赖口径不变;课件变更即回待审核。
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("缺少上传文件")
@@ -320,11 +460,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 {
@@ -332,57 +475,114 @@ 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):课件内容变更后需重新核验。 // 换课件即回待审核(000157):课件内容变更后需重新审核。
item.VerifyStatus = types.CourseLibraryVerifyPending item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = "" item.ConfirmedBy = ""
item.ConfirmedAt = nil 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 移除课件条目(000164 多课件:按 mid 定位,mid 空 =
// 移除最新一条兼容旧调用):文件与知识库挂接随条目移除,名称登记保留;主字段镜像
// 回退为剩余最新条(无剩余则清空);课件变更即回待审核(000157 同口径)。未跑
// 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)
if err != nil || item == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
list := item.CourseMaterialList()
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.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
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 == "" {
@@ -400,21 +600,26 @@ 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.MaterialName = name
}
// 换课件即回待审核(000157):课件内容变更后需重新审核。
item.VerifyStatus = types.CourseLibraryVerifyPending item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = "" item.ConfirmedBy = ""
item.ConfirmedAt = nil 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 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
} }
@@ -0,0 +1,269 @@
package service
import (
"context"
"encoding/json"
"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
}
// 审核(000163:核验升级为审核,审核通过即自动发布):
// - 课程权限必填:perm 两列与 suitable_members 均为空的课程整批拒绝;
// - 已传课件的课程审核通过即自动发布(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: "全部"}
otherDept := &types.TrainingCourseLibrary{ID: "cl-other", Name: "别部门课程", OwnerDeptID: "dept-2", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-2"}
for _, item := range []*types.TrainingCourseLibrary{noPerm, permAndFile, permNoFile, 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())
// 部门不匹配:跳过,无可用条目报错。
_, 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, permNoFile.ID, otherDept.ID}, "u-verifier", "dept-1")
require.NoError(t, err)
require.EqualValues(t, 2, res.Verified)
require.EqualValues(t, 1, res.Skipped)
require.EqualValues(t, 1, res.AutoPublished)
require.Equal(t, []string{"权限缺课件课程"}, 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.CourseLibraryVerifyConfirmed, 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):绑定带出名称/类型,不覆盖
// 计划侧 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"], "软删题库不应计入")
}
@@ -0,0 +1,107 @@
package service
import (
"context"
"path/filepath"
"testing"
"academy/internal/application/repository"
"academy/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// newMineEnrolledFixture 构建 sqlite + 真实仓储的 trainingService,专测
// ListMyEnrolledCourseIDs(我的培训「我参加」判定数据源)。
func newMineEnrolledFixture(t *testing.T) (*trainingService, *gorm.DB, uint64) {
t.Helper()
db, err := gorm.Open(
sqlite.Open(filepath.Join(t.TempDir(), "training_mine_enrolled.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.OrgEmployee{}, &types.TrainingCourseSession{}, &types.TrainingEnrollment{},
))
const tenantID = uint64(42)
svc := &trainingService{repo: repository.NewTrainingRepository(db), db: db}
return svc, db, tenantID
}
// seedMember 建 org_employees 档案(同空间同用户唯一,复用场景自行多次挂名单)。
func seedMember(t *testing.T, db *gorm.DB, tenantID uint64, userID string) (memberID string) {
t.Helper()
member := types.OrgEmployee{ID: trainingNewID(), TenantID: tenantID, UserID: userID, Status: "active"}
require.NoError(t, db.Create(&member).Error)
return member.ID
}
// seedEnrollment 为指定成员落一条 场次+名单 链路,返回名单行(供软删用例复用)。
func seedEnrollment(t *testing.T, db *gorm.DB, tenantID uint64, memberID, courseID string) *types.TrainingEnrollment {
t.Helper()
sess := types.TrainingCourseSession{ID: trainingNewID(), TenantID: tenantID, CourseID: courseID, Status: "scheduled"}
require.NoError(t, db.Create(&sess).Error)
row := &types.TrainingEnrollment{ID: trainingNewID(), TenantID: tenantID, SessionID: sess.ID, MemberID: memberID}
require.NoError(t, db.Create(row).Error)
return row
}
// 我的培训「我参加」:名单命中返回课程 id,跨场次/跨课程去重正确。
func TestListMyEnrolledCourseIDs_HitsAndDistinct(t *testing.T) {
svc, db, tenantID := newMineEnrolledFixture(t)
ctx := context.Background()
// 课程A两条场次名单(去重为一个 id)+ 课程B一条名单
memberID := seedMember(t, db, tenantID, "user-liu")
seedEnrollment(t, db, tenantID, memberID, "course-A")
seedEnrollment(t, db, tenantID, memberID, "course-A")
seedEnrollment(t, db, tenantID, memberID, "course-B")
ids, err := svc.ListMyEnrolledCourseIDs(ctx, tenantID, "user-liu")
require.NoError(t, err)
require.ElementsMatch(t, []string{"course-A", "course-B"}, ids)
}
// 排除口径:软删名单/软删场次/他人名单/其他空间名单均不进「我参加」。
func TestListMyEnrolledCourseIDs_ExcludesDeletedAndForeign(t *testing.T) {
svc, db, tenantID := newMineEnrolledFixture(t)
ctx := context.Background()
// 命中一条基线(course-keep)
memberID := seedMember(t, db, tenantID, "user-liu")
seedEnrollment(t, db, tenantID, memberID, "course-keep")
// 软删名单(course-soft-del)
rowDel := seedEnrollment(t, db, tenantID, memberID, "course-soft-del")
require.NoError(t, db.Delete(rowDel).Error)
// 场次软删(course-sess-del)
rowGone := seedEnrollment(t, db, tenantID, memberID, "course-sess-del")
require.NoError(t, db.Model(&types.TrainingCourseSession{}).
Where("id = ?", rowGone.SessionID).Delete(&types.TrainingCourseSession{}).Error)
// 他人名单(course-other-member):同会话名单换人不影响本人判定
otherID := seedMember(t, db, tenantID, "user-other")
seedEnrollment(t, db, tenantID, otherID, "course-other-member")
// 其他空间(tenant 43)同名用户名单
otherTenantID := seedMember(t, db, tenantID+1, "user-liu")
seedEnrollment(t, db, tenantID+1, otherTenantID, "course-other-tenant")
ids, err := svc.ListMyEnrolledCourseIDs(ctx, tenantID, "user-liu")
require.NoError(t, err)
require.Equal(t, []string{"course-keep"}, ids)
}
// 无培训档案用户返回空集不报错(与 ListMyLearningTasks 同口径)。
func TestListMyEnrolledCourseIDs_NoMemberReturnsEmpty(t *testing.T) {
svc, _, tenantID := newMineEnrolledFixture(t)
ids, err := svc.ListMyEnrolledCourseIDs(context.Background(), tenantID, "user-without-profile")
require.NoError(t, err)
require.Empty(t, ids)
}
+3 -2
View File
@@ -26,10 +26,11 @@ func (s *trainingService) CheckinFor(ctx context.Context, tenantID uint64, opera
return nil, errors.NewNotFoundError("成员不存在") return nil, errors.NewNotFoundError("成员不存在")
} }
if target.UserID == operatorUserID { if target.UserID == operatorUserID {
return s.Checkin(ctx, tenantID, operatorUserID, token, lat, lng, channel) return s.Checkin(ctx, tenantID, operatorUserID, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: channel})
} }
// 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。 // 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。
record, err := s.Checkin(ctx, tenantID, target.UserID, token, lat, lng, "proxy") // 代录不携工号/nonce:工号严格名单硬拒与防重放仅约束学员扫码链路。
record, err := s.Checkin(ctx, tenantID, target.UserID, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: "proxy"})
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -0,0 +1,373 @@
package service
// 企微扫码签到免登(2026-11 需求):
//
// 讲师端二维码(每 rotation_sec=5 分钟惰性轮换)→ 学员企微「扫一扫」→ 落地页
// → snsapi_base 静默授权 → code 换 userid → org_employees.wecom_userid 反查
// 培训档案 → 签发平台 JWT(签到即自动登录,SessionResponseForUser 与
// /auth/login 同构)→ 落地页点击「签到」→ 走 Checkin 规则引擎。
//
// 身份映射完全复用既有 wecom_userid 绑定(组织架构页维护/OA 同步);企微凭据
// 复用租户 IM webhook 渠道(与推送同一套 corp_id/agent_secret/corp_agent_id)。
// 本文件不 import internal/im:客户端经 WecomOAuthBackend 接口由容器注入
// (wecompush.Backend 适配,与 WecomPushBackend 同一模式,避免 im 测试环)。
import (
"context"
"net"
neturl "net/url"
"os"
"strings"
"time"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"gorm.io/gorm"
)
// WecomOAuthClient 企微网页授权客户端(按租户解析出的自建应用凭据)。
type WecomOAuthClient interface {
// BuildOAuthAuthorizeURL 拼 snsapi_base 静默授权链接(state=签到码 token)。
BuildOAuthAuthorizeURL(redirectURI, state string) string
// GetOAuthUserID 网页授权 code 换企微 userid(code 一次性,5 分钟有效)。
GetOAuthUserID(ctx context.Context, code string) (string, error)
}
// WecomOAuthBackend resolves the per-tenant OAuth client. Implemented by
// internal/im/wecompush (which owns the internal/im dependency the service
// layer must avoid — same rationale as WecomPushBackend).
type WecomOAuthBackend interface {
OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (WecomOAuthClient, error)
}
// WecomCheckinAuthURL implements interfaces.TrainingService.
// GET /training/wecom/checkin-auth?token=xxx — 匿名入口:校验签到码后返回
// 企微授权链接;redirectURI 由落地页按当前域名拼出(kbt/kb 跟随二维码环境)。
func (s *trainingService) WecomCheckinAuthURL(ctx context.Context, token, redirectURI string) (string, error) {
token = strings.TrimSpace(token)
if token == "" {
return "", errors.NewBadRequestError("缺少签到码")
}
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil {
return "", errors.NewBadRequestError("签到码无效或已过期,请联系讲师刷新")
}
if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) {
return "", errors.NewBadRequestError("签到码已更新,请重新扫码")
}
if s.wecomOAuth == nil {
return "", errors.NewInternalServerError("企微免登通道未配置")
}
client, err := s.wecomOAuth.OAuthClientForTenant(ctx, s.db, code.TenantID)
if err != nil {
// 渠道未配置(corp_id/secret 缺失)是运营配置问题,给可行动的文案。
return "", errors.NewBadRequestError("该空间未配置企微自建应用渠道,请联系管理员在 IM 集成中创建")
}
redirectURI = strings.TrimSpace(redirectURI)
if redirectURI == "" {
return "", errors.NewBadRequestError("缺少回跳地址")
}
if err := validateWecomRedirectHost(redirectURI); err != nil {
return "", err
}
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.
// POST /training/wecom/checkin-session {code, state} — 匿名入口:OAuth code 换
// 身份并签发平台会话(签到即自动登录),同时一次带回落地页数据。
func (s *trainingService) WecomCheckinSession(ctx context.Context, oauthCode, state string) (*types.WecomCheckinSession, error) {
oauthCode, state = strings.TrimSpace(oauthCode), strings.TrimSpace(state)
if oauthCode == "" || state == "" {
return nil, errors.NewBadRequestError("授权参数不完整")
}
if s.wecomOAuth == nil {
return nil, errors.NewInternalServerError("企微免登通道未配置")
}
// state 即签到码 token(前端从落地页 URL 透传);命中当前码,或轮换宽限中的
// 前码 —— 后者覆盖"学员扫码后、OAuth 回跳前恰好轮换"的踩空窗口。
code, prev, err := s.resolveWecomSignCode(ctx, state)
if err != nil {
return nil, err
}
// 1) code → 企微 userid → 绑定反查培训档案(限定签到码所在空间)。
client, err := s.wecomOAuth.OAuthClientForTenant(ctx, s.db, code.TenantID)
if err != nil {
return nil, errors.NewBadRequestError("该空间未配置企微自建应用渠道,请联系管理员在 IM 集成中创建")
}
wecomUserid, err := client.GetOAuthUserID(ctx, oauthCode)
if err != nil {
logger.Warnf(ctx, "wecom checkin: oauth code exchange failed: %v", err)
return nil, errors.NewUnauthorizedError("企微授权失败或已过期,请重新扫码")
}
member, err := s.repo.GetMemberByWecomUserid(ctx, code.TenantID, wecomUserid)
if err != nil || member == nil {
return nil, errors.NewForbiddenError("未找到您的培训档案:企微账号未绑定或不在该空间培训名册,请联系人事在组织架构中维护")
}
// 2) 平台用户 + 签发会话(落点沿用登录解析,与 /auth/login 同构)。
user, err := s.users.GetUserByID(ctx, member.UserID)
if err != nil || user == nil {
return nil, errors.NewForbiddenError("培训档案未关联平台账号,请联系管理员")
}
login, err := s.users.SessionResponseForUser(ctx, user)
if err != nil {
logger.Warnf(ctx, "wecom checkin: issue session failed for user %s: %v", user.ID, err)
return nil, errors.NewInternalServerError("自动登录失败,请稍后重试")
}
// 3) 落地页数据一次带回(课程信息/倒计时/名单/重复标记)。
page, err := s.buildWecomCheckinPage(ctx, code, member, prev)
if err != nil {
return nil, err
}
return &types.WecomCheckinSession{LoginResponse: *login, WecomCheckinPage: *page}, nil
}
// WecomCheckinPage implements interfaces.TrainingService.
// POST /training/wecom/checkin-page {token} — 已登录用户(PC 讲师自测/企微内已
// 有会话)取落地页数据;租户走常规培训空间解析。
func (s *trainingService) WecomCheckinPage(ctx context.Context, tenantID uint64, userID, token string) (*types.WecomCheckinPage, error) {
code, err := s.repo.GetSignCodeByToken(ctx, tenantID, strings.TrimSpace(token))
if err != nil || code == nil {
return nil, errors.NewBadRequestError("签到码无效或已过期,请联系讲师刷新")
}
member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID)
if err != nil || member == nil {
return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
}
page, err := s.buildWecomCheckinPage(ctx, code, member, false)
if err != nil {
return nil, err
}
return page, nil
}
// ---------------------------------------------------------------------------
// 内部工具
// ---------------------------------------------------------------------------
// resolveWecomSignCode 按 state(token)定位签到码:优先当前码;未命中时接受
// 轮换宽限中的前码(rotation_grace_sec,默认 30s)。返回 (码行, 是否前码, 错误)。
func (s *trainingService) resolveWecomSignCode(ctx context.Context, token string) (*types.TrainingSignCode, bool, error) {
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil {
return nil, false, errors.NewBadRequestError("签到码无效或已过期,请重新扫码")
}
if code.Token == token {
return code, false, nil
}
// 前码:宽限期内放行(与 Checkin 的 prev-token 宽限同口径)。
grace := time.Duration(s.ruleFloat(ctx, code.TenantID, types.RuleKeySignPolicy, "rotation_grace_sec", 30)) * time.Second
if code.PrevExpireAt == nil || time.Now().After(code.PrevExpireAt.Add(grace)) {
return nil, false, errors.NewBadRequestError("签到码已更新,请重新扫码")
}
return code, true, nil
}
// buildWecomCheckinPage 组装落地页载荷:课程/场次摘要 + 当前成员名单/重复标记。
// member 可为 nil(匿名落地页,工号未输入):此时跳过姓名补齐与名单/重复标记,
// 仅返回课程信息与签到码有效期。
func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types.TrainingSignCode, member *types.TrainingMember, prevToken bool) (*types.WecomCheckinPage, error) {
// 姓名:档案 UserName 为联查字段,直查不回填;用平台账号显示名补齐,
// 落地页「工号 + 姓名」确认行展示(免登链路学员核对身份用)。
if member != nil && s.users != nil && member.UserName == "" {
if u, uerr := s.users.GetUserByID(ctx, member.UserID); uerr == nil && u != nil {
if u.DisplayName != "" {
member.UserName = u.DisplayName
} else {
member.UserName = u.Username
}
}
}
page := &types.WecomCheckinPage{
Member: member,
SessionID: code.SessionID,
SignExpireAt: code.ExpireAt,
}
session, err := s.repo.GetSession(ctx, code.TenantID, code.SessionID)
if err != nil || session == nil {
return nil, errors.NewBadRequestError("课程场次不存在")
}
course, err := s.repo.GetCourse(ctx, code.TenantID, session.CourseID)
if err != nil || course == nil {
return nil, errors.NewBadRequestError("课程不存在")
}
// 前码宽限进来时,倒计时以旧码剩余时间为准(归零即须重新扫码)。
if prevToken && code.PrevExpireAt != nil {
page.SignExpireAt = code.PrevExpireAt
}
// 讲师姓名:档案 UserName 为联查字段,直查不回填,取平台账号显示名兜底。
lecturerName := ""
if course.LecturerID != "" {
if lecturer, lerr := s.repo.GetMember(ctx, code.TenantID, course.LecturerID); lerr == nil && lecturer != nil && lecturer.UserName != "" {
lecturerName = lecturer.UserName
}
}
if lecturerName == "" && course.LecturerID != "" {
if lu, lerr := s.users.GetUserByID(ctx, course.LecturerID); lerr == nil && lu != nil {
lecturerName = lu.DisplayName
if lecturerName == "" {
lecturerName = lu.Username
}
}
}
page.Course = &types.WecomCheckinCourse{
CourseID: course.ID,
CourseName: course.Name,
LecturerName: lecturerName,
StartAt: session.StartAt,
EndAt: session.EndAt,
Location: session.Location,
Status: session.Status,
// 当天性判定与 Checkin 的 same-day 规则同一口径(北京时间)。
CanSignToday: session.StartAt != nil && sameBeijingDay(time.Now(), *session.StartAt),
}
// 名单/重复标记:前端提前渲染按钮态(置灰/已签到),提交时后端仍强校验兜底。
// 匿名模式(member 为 nil,工号未输入)无从判定,交给提交时强校验。
if member != nil {
if roster, rerr := s.repo.ListEnrollments(ctx, code.TenantID, session.ID); rerr == nil {
for _, e := range roster {
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)
}
}
}
return resp, nil
}
// sameBeijingDay 判断两个时刻是否同一「北京时间」自然日(签到当天性校验统一
// 口径;固定 +8 偏移,不依赖服务器时区,与前端 fmtBeijingTime 一致)。
func sameBeijingDay(a, b time.Time) bool {
cst := time.FixedZone("CST", 8*3600)
ay, am, ad := a.In(cst).Date()
by, bm, bd := b.In(cst).Date()
return ay == by && am == bm && ad == bd
}
+33
View File
@@ -324,6 +324,39 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
}, nil }, nil
} }
// SessionResponseForUser assembles a login response for an already
// authenticated identity (2026-11 企微扫码签到免登):落点沿用登录解析(最近活跃
// 租户偏好优先),token/tenant/memberships 与 /auth/login 同构,前端复用同一
// 持久化路径完成"签到即自动登录"。
func (s *userService) SessionResponseForUser(ctx context.Context, user *types.User) (*types.LoginResponse, error) {
if user == nil {
return nil, errors.New("user is required")
}
resolvedTenantID := s.resolveLoginTenantID(ctx, user)
accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, resolvedTenantID)
if err != nil {
logger.Errorf(ctx, "Failed to generate session tokens: %v", err)
return nil, fmt.Errorf("generate session tokens: %w", err)
}
var tenant *types.Tenant
if resolvedTenantID > 0 {
if t, terr := s.tenantService.GetTenantByID(ctx, resolvedTenantID); terr == nil {
tenant = t
} else {
logger.Warn(ctx, "Failed to get tenant info")
}
}
return &types.LoginResponse{
Success: true,
Message: "Login successful",
User: user,
ActiveTenant: tenant,
Memberships: s.buildMembershipsForUser(ctx, user, tenant),
Token: accessToken,
RefreshToken: refreshToken,
}, nil
}
// buildMembershipsForUser returns the user's tenant memberships projected // buildMembershipsForUser returns the user's tenant memberships projected
// into the login-response shape. activeTenant (if non-nil and matching one // into the login-response shape. activeTenant (if non-nil and matching one
// of the rows) is used to reuse its already-fetched name without a second // of the rows) is used to reuse its already-fetched name without a second
+17
View File
@@ -413,6 +413,12 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Training domain (企业培训业务域): repo → service(interface) → handler. // Training domain (企业培训业务域): repo → service(interface) → handler.
must(container.Provide(repository.NewTrainingRepository)) must(container.Provide(repository.NewTrainingRepository))
must(container.Provide(service.NewTrainingService, dig.As(new(interfaces.TrainingService)))) must(container.Provide(service.NewTrainingService, dig.As(new(interfaces.TrainingService))))
// 企微扫码签到免登后端(2026-11 需求):与 scheduler 的 wecom 适配同一来源
// (trainingWecomBackend 包装 wecompush.Backend),经接口注入 service 层,
// service 不 import internal/im(同 WecomPushBackend 的防环理由)。
must(container.Provide(func() service.WecomOAuthBackend {
return trainingWecomBackend{wecompush.Backend{}}
}))
// Session service (depends on agent service) // Session service (depends on agent service)
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed // SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
@@ -2181,6 +2187,17 @@ func (b trainingWecomBackend) TenantWecomUserIDs(ctx context.Context, db *gorm.D
return b.inner.TenantWecomUserIDs(ctx, db, tenantID, userIDs) return b.inner.TenantWecomUserIDs(ctx, db, tenantID, userIDs)
} }
// OAuthClientForTenant boxes the concrete *wecom.ProactiveClient into
// service.WecomOAuthClient (培训扫码签到免登:snsapi_base 授权链接 + code 换
// userid;同一自建应用凭据,复用 ClientForTenant 的渠道解析)。
func (b trainingWecomBackend) OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (service.WecomOAuthClient, error) {
client, err := b.inner.OAuthClientForTenant(ctx, db, tenantID)
if err != nil {
return nil, err
}
return client, nil
}
// startTrainingScheduler starts the training WeCom reminder scheduler and // startTrainingScheduler starts the training WeCom reminder scheduler and
// registers cleanup. Best-effort like the other background runners. // registers cleanup. Best-effort like the other background runners.
func startTrainingScheduler(scheduler *service.TrainingScheduler, cleaner interfaces.ResourceCleaner) { func startTrainingScheduler(scheduler *service.TrainingScheduler, cleaner interfaces.ResourceCleaner) {
+13
View File
@@ -48,6 +48,9 @@ type KnowledgeBaseHandler struct {
// default handle mode is available. // default handle mode is available.
fileService interfaces.FileService fileService interfaces.FileService
storageResolver interfaces.StorageBackendResolver storageResolver interfaces.StorageBackendResolver
// bootstrap 幂等自愈空间开箱默认库(新手入门/企业培训课件/题库),挂在
// 知识库列表读路径上补齐存量空间缺失的默认库;可为 nil(测试桩)。
bootstrap interfaces.TenantBootstrapService
} }
// NewKnowledgeBaseHandler creates a new knowledge base handler instance // NewKnowledgeBaseHandler creates a new knowledge base handler instance
@@ -63,6 +66,7 @@ func NewKnowledgeBaseHandler(
fileService interfaces.FileService, fileService interfaces.FileService,
storageResolver interfaces.StorageBackendResolver, storageResolver interfaces.StorageBackendResolver,
profileService interfaces.KnowledgeBaseProfileService, profileService interfaces.KnowledgeBaseProfileService,
bootstrap interfaces.TenantBootstrapService,
) *KnowledgeBaseHandler { ) *KnowledgeBaseHandler {
return &KnowledgeBaseHandler{ return &KnowledgeBaseHandler{
cfg: cfg, cfg: cfg,
@@ -76,6 +80,7 @@ func NewKnowledgeBaseHandler(
userService: userService, userService: userService,
fileService: fileService, fileService: fileService,
storageResolver: storageResolver, storageResolver: storageResolver,
bootstrap: bootstrap,
} }
} }
@@ -639,6 +644,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
return return
} }
// 开箱默认库惰性自愈(幂等/fail-open):注册引导是一次性动作,存量空间因
// 引导当时失败或保留租户 id 碰撞(migration 000160 前首空间占住 10000)
// 而缺失默认库时,访问列表即补齐——培训课件/题库两库恒补,新手入门仅
// 零库空间补建。补建后本次查询即可见。
if h.bootstrap != nil {
h.bootstrap.EnsureTenantDefaultKnowledgeBases(ctx)
}
// Get all knowledge bases for this tenant // Get all knowledge bases for this tenant
kbs, err := h.service.ListKnowledgeBases(ctx) kbs, err := h.service.ListKnowledgeBases(ctx)
if err != nil { if err != nil {
+66 -2
View File
@@ -2,6 +2,7 @@ package orgcenter
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"strconv" "strconv"
@@ -199,6 +200,69 @@ func (h *Handler) ListPlatformUsers(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": users}) c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
} }
// ---------------------------------------------------------------------------
// 归属空间收编(登录默认落点;路由层 Owner 限定,与成员批量导入同权限级别)
// ---------------------------------------------------------------------------
// orgAdoptMaxUsers 单次收编人数上限(与成员批量导入行数上限同量级,防超大批次)。
const orgAdoptMaxUsers = 2000
// ListAdoptableUsers GET /org/employees/adoptable — 收编预览:归属空间不在
// 本空间的活跃成员(员工首登开了个人空间时,登录会落进个人空间看不到本空间
// 维护的组织架构,管理员用收编把默认落点改回本空间)。
func (h *Handler) ListAdoptableUsers(c *gin.Context) {
users, err := h.svc.ListAdoptableUsers(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
}
// adoptHomeTenantRequest is the body of POST /org/employees/adopt-home.
type adoptHomeTenantRequest struct {
UserIDs []string `json:"user_ids" binding:"required,min=1"`
}
// AdoptHomeTenant POST /org/employees/adopt-home — 批量收编归属空间到本空间。
// 只改成员的登录默认落点(users.tenant_id + 最近活跃租户偏好),不动成员关系
// 与个人空间数据;逐条跳过非本空间成员等情形并回传原因。
func (h *Handler) AdoptHomeTenant(c *gin.Context) {
ctx := c.Request.Context()
var req adoptHomeTenantRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if len(req.UserIDs) > orgAdoptMaxUsers {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("单次最多收编 %d 名成员", orgAdoptMaxUsers)))
return
}
// 去重保序:重复/空 id 只收编一次,统计口径不重复计数。
seen := make(map[string]struct{}, len(req.UserIDs))
userIDs := make([]string, 0, len(req.UserIDs))
for _, id := range req.UserIDs {
if id == "" {
continue
}
if _, dup := seen[id]; dup {
continue
}
seen[id] = struct{}{}
userIDs = append(userIDs, id)
}
if len(userIDs) == 0 {
_ = c.Error(errors.NewBadRequestError("请选择要收编的成员"))
return
}
result, err := h.svc.AdoptHomeTenant(ctx, callerTenantID(c), userIDs)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 模块角色绑定 // 模块角色绑定
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -216,8 +280,8 @@ func (h *Handler) ListModuleMembers(c *gin.Context) {
// putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id. // putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id.
type putModuleMemberRequest struct { type putModuleMemberRequest struct {
Roles []string `json:"roles"` Roles []string `json:"roles"`
Extra map[string]any `json:"extra"` Extra map[string]any `json:"extra"`
} }
// PutModuleMember PUT /org/modules/:module_key/members/:employee_id // PutModuleMember PUT /org/modules/:module_key/members/:employee_id
+327 -51
View File
@@ -32,12 +32,41 @@ func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotifi
return &Handler{svc: svc, pusher: pusher} return &Handler{svc: svc, pusher: pusher}
} }
// trainingTenantContextKey 培训域解析后的数据空间租户 id(000160):由
// TrainingTenantResolution 中间件写入,callerTenantID 优先读取。
const trainingTenantContextKey = "training_tenant_id"
// TrainingTenantResolution 企业培训数据空间解析中间件(000160):认证守卫之后
// 执行,按「当前空间有培训档案优先,否则回退员工档案所在空间」解析培训域实际
// 读写的租户并写入上下文;本组所有 handler 的 callerTenantID 均取解析值 ——
// 同一组织的人员切换到任意工作区,都能看到并参与其档案所属组织的企业培训。
func (h *Handler) TrainingTenantResolution() gin.HandlerFunc {
return func(c *gin.Context) {
active := c.GetUint64(types.TenantIDContextKey.String())
userID := callerUserID(c)
if active != 0 && userID != "" {
if resolved, err := h.svc.ResolveTrainingTenant(c.Request.Context(), active, userID); err == nil && resolved != 0 {
c.Set(trainingTenantContextKey, resolved)
// 执行租户随培训空间同步回落(000160):课件文件流(GetKnowledgeFile)、
// 培训知识库 ensure 等按 ctx 租户读写的服务链路才落在档案所在空间;
// caller 身份保持当前工作区不变,授权口径不受影响。
c.Request = c.Request.WithContext(types.WithExecutionTenant(c.Request.Context(), resolved))
}
}
c.Next()
}
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 请求上下文辅助 // 请求上下文辅助
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// callerTenantID reads the tenant id injected by the auth middleware. // callerTenantID reads the tenant id injected by the auth middleware, or the
// training-resolved tenant (000160) when the route group middleware resolved one.
func callerTenantID(c *gin.Context) uint64 { func callerTenantID(c *gin.Context) uint64 {
if v := c.GetUint64(trainingTenantContextKey); v != 0 {
return v
}
return c.GetUint64(types.TenantIDContextKey.String()) return c.GetUint64(types.TenantIDContextKey.String())
} }
@@ -400,6 +429,18 @@ func (h *Handler) Me(c *gin.Context) {
_ = c.Error(err) _ = c.Error(err)
return return
} }
// 联查部门名(000160):员工档案只存 dept_id,前端课程目录按部门名匹配
// 「适合人员」、表单默认值展示均需要名称;档案无部门时保持空串。
if member.DeptID != "" {
if depts, err := h.svc.ListDepts(ctx, callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
member.DeptName = d.Name
break
}
}
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member}) c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
} }
@@ -436,9 +477,12 @@ func (h *Handler) ListDemandYears(c *gin.Context) {
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/ // 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。 // 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
type saveDemandRequest struct { type saveDemandRequest struct {
ID string `json:"id"` ID string `json:"id"`
Year int `json:"year"` Year int `json:"year"`
DeptID string `json:"dept_id"` DeptID string `json:"dept_id"`
// DeptName Excel「部门」列原始值(仅批量导入部门归属校验用,000158:全部行
// 必须为导入人本人部门;在线提报不传,服务端强制按提报人部门落库)。
DeptName string `json:"dept_name"`
CourseName string `json:"course_name" binding:"required"` CourseName string `json:"course_name" binding:"required"`
Plant string `json:"plant"` Plant string `json:"plant"`
Category string `json:"category"` Category string `json:"category"`
@@ -504,14 +548,23 @@ func (h *Handler) SaveDemand(c *gin.Context) {
return return
} }
} }
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。 // 部门口径(000158):所属部门必须为填报人本人部门——新建强制按提报人所在
deptID := trimSpace(req.DeptID) // 部门(org_employees.dept_id)落库,忽略请求值防绕过;编辑保留原部门(人事
if deptID == "" { // 代改也不覆盖归属)。提报人无部门档案时阻断,先由人事在组织中心维护。
if existing != nil { var deptID string
deptID = existing.DeptID if existing != nil {
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil { deptID = existing.DeptID
deptID = member.DeptID } else {
member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
} }
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再提报"))
return
}
deptID = member.DeptID
} }
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{ demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
ID: req.ID, Year: req.Year, DeptID: deptID, ID: req.ID, Year: req.Year, DeptID: deptID,
@@ -575,6 +628,9 @@ func (h *Handler) ListPosts(c *gin.Context) {
} }
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。 // ImportDemands POST /training/demands/import — 调研表在线化批量导入。
// 部门口径(000158):全部行必须为导入人本人部门(org_employees.dept_id,全员
// 严格,人事也不例外);部门列留空视为默认导入人部门,其余任一行不符即整批
// 拒绝。导入人无部门档案时阻断,先由人事在组织中心维护。
func (h *Handler) ImportDemands(c *gin.Context) { func (h *Handler) ImportDemands(c *gin.Context) {
ctx := c.Request.Context() ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) { if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
@@ -587,10 +643,47 @@ func (h *Handler) ImportDemands(c *gin.Context) {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error())) _ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return return
} }
tenantID, userID := callerTenantID(c), callerUserID(c)
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
if err != nil {
_ = c.Error(err)
return
}
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再导入"))
return
}
// 整批部门预检:任一行部门与导入人不符即拒绝,不做部分导入。
// 通过口径:行部门 id 与本人一致,或部门列全空(默认导入人部门)。
myDeptName := h.deptNameOf(ctx, tenantID, member.DeptID)
violations := make([]string, 0, len(req.Demands))
for i, item := range req.Demands {
deptID, deptName := trimSpace(item.DeptID), trimSpace(item.DeptName)
if deptID == "" && deptName == "" {
continue
}
if deptID == member.DeptID {
continue
}
if deptName == "" {
deptName = h.deptNameOf(ctx, tenantID, deptID)
}
if deptName == "" {
deptName = deptID
}
violations = append(violations, fmt.Sprintf("第%d行(%s)", i+1, deptName))
}
if len(violations) > 0 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf(
"导入失败:第%s行部门与您所在部门(%s)不一致,仅可导入本人部门的需求表",
strings.Join(violations, "、"), myDeptName)))
return
}
demands := make([]*types.TrainingDemand, 0, len(req.Demands)) demands := make([]*types.TrainingDemand, 0, len(req.Demands))
for _, item := range req.Demands { for _, item := range req.Demands {
demands = append(demands, &types.TrainingDemand{ demands = append(demands, &types.TrainingDemand{
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName, // 部门强制为导入人本人部门:部门列留空的行在此默认,其余已通过预检。
Year: item.Year, DeptID: member.DeptID, CourseName: item.CourseName,
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount, Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID, Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType), LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
@@ -598,16 +691,34 @@ func (h *Handler) ImportDemands(c *gin.Context) {
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark, PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
}) })
} }
result, err := h.svc.ImportDemands(ctx, callerTenantID(c), demands, callerUserID(c)) result, coursesCreated, err := h.svc.ImportDemands(ctx, tenantID, demands, userID)
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。 // 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands) h.syncDemandLecturerToLibrary(ctx, tenantID, userID, demands)
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。 // 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands) notified := h.notifyDemandVerify(ctx, tenantID, demands)
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}}) c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"imported": len(result), "notified": notified, "courses_created": coursesCreated}})
}
// deptNameOf 部门 id → 名称(导入报错文案用;查不到时回退展示 id)。
func (h *Handler) deptNameOf(ctx context.Context, tenantID uint64, deptID string) string {
if trimSpace(deptID) == "" {
return ""
}
depts, err := h.svc.ListDepts(ctx, tenantID)
if err != nil {
return deptID
}
for _, d := range depts {
if d != nil && d.ID == deptID {
return d.Name
}
}
return deptID
} }
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄): // demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
@@ -681,10 +792,13 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
PostScope: demand.PostScope, PostScope: demand.PostScope,
} }
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源; // 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息), // 课程管理关联(000158):需求填报/导入时已按名称精准匹配并回填
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。 // library_course_id(未命中自动新增待核验课程),此处直接采用;存量需求
// 无值时回退课程管理同名扫描兜底(计划侧自动带出并锁定课程信息)。
course.SourceDemandID = demand.ID course.SourceDemandID = demand.ID
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil { if trimSpace(demand.LibraryCourseID) != "" {
course.LibraryCourseID = demand.LibraryCourseID
} else if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
for _, item := range libItems { for _, item := range libItems {
if item != nil && item.Name == demand.CourseName { if item != nil && item.Name == demand.CourseName {
course.LibraryCourseID = item.ID course.LibraryCourseID = item.ID
@@ -901,47 +1015,75 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
} }
} }
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存) // syncDemandLecturerToLibrary 需求课程信息回写课程管理(000156/000161):需求
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后 // (导入/在线保存/编辑)所关联的课程管理条目——优先 demand.library_course_id
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。 // (000158 自动匹配),无值回退同名匹配——讲师与条目不一致时以需求为准更新;
// 000161 扩展:分类/适合人员(需求侧改后)同样回写。SaveCourseLibraryItem 的
// 编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须重新签核。
// 同批同名取首条。fail-open:失败仅记日志不阻断保存/导入。
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) { func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
byID := map[string]*types.TrainingDemand{}
byName := map[string]*types.TrainingDemand{} byName := map[string]*types.TrainingDemand{}
for _, d := range demands { for _, d := range demands {
if d == nil || trimSpace(d.CourseName) == "" { if d == nil || trimSpace(d.CourseName) == "" {
continue continue
} }
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" { if id := trimSpace(d.LibraryCourseID); id != "" {
if _, ok := byID[id]; !ok {
byID[id] = d
}
continue continue
} }
if _, ok := byName[d.CourseName]; !ok { if _, ok := byName[d.CourseName]; !ok {
byName[d.CourseName] = d byName[d.CourseName] = d
} }
} }
if len(byName) == 0 { if len(byID) == 0 && len(byName) == 0 {
return return
} }
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}) items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil { if err != nil {
logger.Error(ctx, "Failed to list course library for lecturer sync", err) logger.Error(ctx, "Failed to list course library for demand sync", err)
return return
} }
for _, item := range items { for _, item := range items {
if item == nil { if item == nil {
continue continue
} }
d, ok := byName[item.Name] d, ok := byID[item.ID]
if !ok {
d, ok = byName[item.Name]
}
if !ok { if !ok {
continue continue
} }
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal) lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt { if lecturerID != "" {
lecturerExt = ""
}
hasLecturer := lecturerID != "" || lecturerExt != ""
category, suitable := trimSpace(d.Category), trimSpace(d.PostScope)
// 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止
// 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。
changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) ||
(category != "" && item.Category != category) ||
(suitable != "" && item.SuitableMembers != suitable)
if !changed {
continue continue
} }
updated := *item updated := *item
updated.LecturerID = lecturerID if hasLecturer {
updated.LecturerExternal = lecturerExt updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
}
if category != "" {
updated.Category = category
}
if suitable != "" {
updated.SuitableMembers = 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 lecturer to course library", err) logger.Error(ctx, "Failed to sync demand course info to course library", err)
continue continue
} }
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。 // 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
@@ -1221,26 +1363,8 @@ func (h *Handler) PublishCourse(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
} }
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。 // 发布前置校验(线上课件/线下讲师等)统一收口在 service PublishCourse:
course, err := h.svc.GetCourse(ctx, callerTenantID(c), c.Param("id")) // 线上课件认计划自带或课程管理自带课件,考题非必填。
if err != nil {
_ = c.Error(err)
return
}
if course.Mode == "online" {
materials, err := h.svc.ListMaterials(ctx, callerTenantID(c), course.ID)
if err != nil {
_ = c.Error(err)
return
}
if len(materials) == 0 {
_ = c.Error(errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)"))
return
}
} else if trimSpace(course.LecturerID) == "" {
_ = c.Error(errors.NewBadRequestError("线下课程发布前需先指定讲师"))
return
}
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c)) published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
@@ -1664,6 +1788,12 @@ type CheckinRequest struct {
Channel string `json:"channel"` Channel string `json:"channel"`
// MemberID 可选:讲师/课长/人事现场代扫码/补录。 // MemberID 可选:讲师/课长/人事现场代扫码/补录。
MemberID string `json:"member_id"` MemberID string `json:"member_id"`
// EmployeeNo 录入工号(2026-11 扫码签到页必带):非空时启用严格校验
// (工号与档案一致 + 必须在「参加人员」名单 + 当天性 + nonce 防重放)。
EmployeeNo string `json:"employee_no"`
// Nonce 随机时间戳防重放;ClientTS 客户端提交时刻毫秒(时钟偏差校验)。
Nonce string `json:"nonce"`
ClientTS int64 `json:"client_ts"`
} }
// Checkin POST /training/sign-records/checkin — 学员扫码签到(带定位校验); // Checkin POST /training/sign-records/checkin — 学员扫码签到(带定位校验);
@@ -1687,7 +1817,15 @@ func (h *Handler) Checkin(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": record}) c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
return return
} }
record, err := h.svc.Checkin(ctx, callerTenantID(c), callerUserID(c), req.Token, req.Lat, req.Lng, req.Channel) record, err := h.svc.Checkin(ctx, callerTenantID(c), callerUserID(c), &types.CheckinInput{
Token: req.Token,
Lat: req.Lat,
Lng: req.Lng,
Channel: req.Channel,
EmployeeNo: req.EmployeeNo,
Nonce: req.Nonce,
ClientTS: req.ClientTS,
})
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
@@ -1695,6 +1833,144 @@ func (h *Handler) Checkin(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": record}) c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
} }
// ---------------------------------------------------------------------------
// 企微扫码签到免登(2026-11 需求):匿名入口,路由直挂 v1 组外 +
// noAuthAPI 白名单 + PublicAuthRateLimit,身份由签到码 token / OAuth code 承载。
// ---------------------------------------------------------------------------
// WecomCheckinAuthRequest is the query of GET /training/wecom/checkin-auth.
// redirect_uri 由落地页按当前域名拼出(测试 kbt / 正式 kb 跟随二维码环境)。
type WecomCheckinAuthRequest struct {
Token string `form:"token" binding:"required"`
RedirectURI string `form:"redirect_uri"`
}
// WecomCheckinAuth GET /training/wecom/checkin-auth — 返回企微 snsapi_base
// 静默授权链接,前端 location.replace 跳转(学员无感)。
func (h *Handler) WecomCheckinAuth(c *gin.Context) {
var q WecomCheckinAuthRequest
if err := c.ShouldBindQuery(&q); err != nil {
_ = c.Error(errors.NewBadRequestError("缺少签到码").WithDetails(err.Error()))
return
}
redirectURI := strings.TrimSpace(q.RedirectURI)
if redirectURI == "" {
// 兜底:按请求 Host 还原落地页地址(独立手机端 H5 路由,反代透传
// X-Forwarded-Proto)。
scheme := "https"
if c.Request.TLS == nil {
if proto := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto")); proto != "" {
scheme = proto
} else {
scheme = "http"
}
}
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)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"authorize_url": url}})
}
// WecomCheckinSessionRequest is the body of POST /training/wecom/checkin-session.
type WecomCheckinSessionRequest struct {
Code string `json:"code" binding:"required"`
State string `json:"state" binding:"required"`
}
// WecomCheckinSession POST /training/wecom/checkin-session — OAuth code 换
// 平台会话(token/refresh_token/user/active_tenant/memberships,与 /auth/login
// 同构,前端复用登录持久化路径即"签到即自动登录")+ 落地页数据。
func (h *Handler) WecomCheckinSession(c *gin.Context) {
var req WecomCheckinSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("授权参数不完整").WithDetails(err.Error()))
return
}
session, err := h.svc.WecomCheckinSession(c.Request.Context(), req.Code, req.State)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": session})
}
// WecomCheckinPageRequest is the body of POST /training/wecom/checkin-page.
type WecomCheckinPageRequest struct {
Token string `json:"token" binding:"required"`
}
// WecomCheckinPage POST /training/wecom/checkin-page — 已登录用户(PC 讲师
// 自测/企微内已有会话)取落地页数据;认证守卫 + 培训空间解析之后。
func (h *Handler) WecomCheckinPage(c *gin.Context) {
var req WecomCheckinPageRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("缺少签到码").WithDetails(err.Error()))
return
}
page, err := h.svc.WecomCheckinPage(c.Request.Context(), callerTenantID(c), callerUserID(c), req.Token)
if err != nil {
_ = c.Error(err)
return
}
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"))
+127 -13
View File
@@ -29,9 +29,13 @@ 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"`
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 +56,8 @@ 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,
Category: req.Category, Category: req.Category,
Type: req.Type, Type: req.Type,
Mode: req.Mode, Mode: req.Mode,
@@ -66,9 +72,85 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。 // ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅 // 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。 // 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
// 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)
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c) if q.Scope == "catalog" {
q.CatalogOnly = true
// 课程权限匹配身份(000163):调用方部门(id+名)+用户 id;无培训档案
// 的调用方部门字段留空(仅见「全部」与未设置权限的课程),不阻断目录。
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 q.CatalogDeptID != "" {
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == q.CatalogDeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
} 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 {
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 {
_ = c.Error(err) _ = c.Error(err)
@@ -77,6 +159,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)。
@@ -185,14 +278,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
@@ -204,15 +298,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
@@ -312,10 +406,30 @@ func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": item}) c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
} }
// RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove
// — 移除课件条目(000164 多课件:body 可选 {mid} 定位条目,缺省移除最新一条;
// 课件变更即回待审核)。
func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
// 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 {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
// 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
@@ -367,6 +367,18 @@ func (h *Handler) ListMyLearningTasks(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": items}) c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
} }
// ListMyEnrolledCourseIds GET /training/my/enrolled-course-ids — 我经场次学员
// 名单报名的课程 id 去重集合(我的培训「我参加」判定数据源,前端与学习任务/
// 讲师/部门范围口径互补;登录即可查,自身名单本身即个人数据)。
func (h *Handler) ListMyEnrolledCourseIds(c *gin.Context) {
ids, err := h.svc.ListMyEnrolledCourseIDs(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": ids})
}
// ListCourseLearningTasks GET /training/learning-tasks/all?course_id= — // ListCourseLearningTasks GET /training/learning-tasks/all?course_id= —
// 按课程返回全员学习任务(人事/课长/讲师的「学习考试」课程学习情况视图)。 // 按课程返回全员学习任务(人事/课长/讲师的「学习考试」课程学习情况视图)。
func (h *Handler) ListCourseLearningTasks(c *gin.Context) { func (h *Handler) ListCourseLearningTasks(c *gin.Context) {
@@ -0,0 +1,90 @@
package training
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubTenantResolution 只覆盖空间解析;被测中间件不触碰其余服务面。
type stubTenantResolution struct {
interfaces.TrainingService
resolved uint64
}
func (s *stubTenantResolution) ResolveTrainingTenant(_ context.Context, _ uint64, _ string) (uint64, error) {
return s.resolved, nil
}
// seedAuthSession 模拟认证中间件 applyAuthSession 的双面写入(gin keys + 请求
// 上下文,含 Caller),保证被测中间件读到与线上一致的请求状态。
func seedAuthSession(c *gin.Context, tenantID uint64, userID string) {
req := httptest.NewRequest(http.MethodGet, "/api/v1/training/courses", nil)
ctx := types.WithCaller(req.Context(), types.Caller{TenantID: tenantID, UserID: userID, Role: types.TenantRoleViewer})
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
c.Request = req.WithContext(ctx)
c.Set(types.TenantIDContextKey.String(), tenantID)
c.Set(types.UserIDContextKey.String(), userID)
}
// TestTrainingTenantResolutionRewritesExecutionTenant 000160 跨空间学员:当前
// 空间无培训档案时,执行租户必须随培训空间回落(课件文件流 GetKnowledgeFile、
// 培训知识库 ensure 等按 ctx 租户读写的链路落在档案所在空间),caller 身份保持
// 当前工作区不变 —— 否则知识库文档按当前空间检索会 404,跨空间鉴权被 403。
func TestTrainingTenantResolutionRewritesExecutionTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
const (
activeTenant = uint64(26080007) // 当前工作区(无培训档案)
archiveTenant = uint64(100) // 员工档案所在空间
userID = "user-1"
)
h := NewHandler(&stubTenantResolution{resolved: archiveTenant}, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
seedAuthSession(c, activeTenant, userID)
h.TrainingTenantResolution()(c)
require.NotNil(t, c.Request)
assert.Equal(t, archiveTenant, c.GetUint64(trainingTenantContextKey))
ctxTenant, ok := types.TenantIDFromContext(c.Request.Context())
require.True(t, ok)
assert.Equal(t, archiveTenant, ctxTenant, "执行租户应回落到培训档案空间")
// caller 身份保持当前工作区:授权口径(空间 RBAC / 知识库共享解析)不受回落影响。
caller := types.CallerFromContext(c.Request.Context())
assert.Equal(t, activeTenant, caller.TenantID)
assert.Equal(t, userID, caller.UserID)
}
// TestTrainingTenantResolutionKeepsActiveTenant 当前空间已有培训档案(或解析
// 未回落)时,行为与升级前一致:租户不变化。
func TestTrainingTenantResolutionKeepsActiveTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
const activeTenant = uint64(300)
h := NewHandler(&stubTenantResolution{resolved: activeTenant}, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
seedAuthSession(c, activeTenant, "user-2")
h.TrainingTenantResolution()(c)
require.NotNil(t, c.Request)
assert.Equal(t, activeTenant, c.GetUint64(trainingTenantContextKey))
ctxTenant, ok := types.TenantIDFromContext(c.Request.Context())
require.True(t, ok)
assert.Equal(t, activeTenant, ctxTenant)
}
+60
View File
@@ -13,6 +13,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
neturl "net/url"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -111,6 +112,65 @@ func (c *ProactiveClient) SendMarkdown(ctx context.Context, userIDs []string, co
return nil return nil
} }
// wecomOAuthAuthorizeBase 企微网页授权入口(公开固定地址,不走 apiBaseURL ——
// 后者可被私有化部署改写,而 OAuth 授权页始终由微信侧提供)。
const wecomOAuthAuthorizeBase = "https://open.weixin.qq.com/connect/oauth2/authorize"
// BuildOAuthAuthorizeURL 企微网页授权链接(snsapi_base 静默免登,培训扫码签到用):
// 学员在企微内置浏览器打开后无感授权,302 回 redirect_uri 并携带 code 与 state。
func (c *ProactiveClient) BuildOAuthAuthorizeURL(redirectURI, state string) string {
return fmt.Sprintf(
"%s?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s&agentid=%d#wechat_redirect",
wecomOAuthAuthorizeBase,
neturl.QueryEscape(c.corpID),
neturl.QueryEscape(redirectURI),
neturl.QueryEscape(state),
c.corpAgentID,
)
}
// GetOAuthUserID 网页授权 code 换用户身份(GET /cgi-bin/auth/getuserinfo):
// snsapi_base 静默授权即可拿到 userid;code 由企微保证一次性(5 分钟有效)。
func (c *ProactiveClient) GetOAuthUserID(ctx context.Context, code string) (string, error) {
accessToken, err := c.getAccessToken(ctx)
if err != nil {
return "", fmt.Errorf("get access token: %w", err)
}
userURL := fmt.Sprintf("%s/cgi-bin/auth/getuserinfo?access_token=%s&code=%s",
c.apiBaseURL, accessToken, neturl.QueryEscape(code))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, userURL, nil)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request oauth userinfo: %w", err)
}
defer resp.Body.Close()
var result struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
UserID string `json:"userid"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("decode oauth userinfo: %w", err)
}
if result.ErrCode != 0 {
// 42001/40014 token 过期类错误清缓存,让下次调用重新获取。
if result.ErrCode == 42001 || result.ErrCode == 40014 {
c.tokenMu.Lock()
c.tokenCache = ""
c.tokenExpAt = time.Time{}
c.tokenMu.Unlock()
}
return "", fmt.Errorf("wecom oauth api error: code=%d msg=%s", result.ErrCode, result.ErrMsg)
}
if result.UserID == "" {
return "", fmt.Errorf("wecom oauth api returned empty userid")
}
return result.UserID, nil
}
// getAccessToken retrieves the WeCom access token with caching. // getAccessToken retrieves the WeCom access token with caching.
func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) { func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) {
c.tokenMu.Lock() c.tokenMu.Lock()
+6
View File
@@ -91,6 +91,12 @@ func (Backend) ClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64
return TenantClient(ctx, db, tenantID) return TenantClient(ctx, db, tenantID)
} }
// OAuthClientForTenant resolves the tenant's client for web OAuth (培训扫码
// 签到免登):同一个自建应用凭据既推消息也做网页授权,复用一套配置。
func (Backend) OAuthClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (*wecom.ProactiveClient, error) {
return TenantClient(ctx, db, tenantID)
}
// TenantWecomUserIDs resolves the userid bindings. // TenantWecomUserIDs resolves the userid bindings.
func (Backend) TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error) { func (Backend) TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error) {
return TenantWecomUserIDs(ctx, db, tenantID, userIDs) return TenantWecomUserIDs(ctx, db, tenantID, userIDs)
+10
View File
@@ -64,6 +64,16 @@ var noAuthAPI = map[string][]string{
// template key + 20-day expiry), never by caller-supplied ids. HEAD is // template key + 20-day expiry), never by caller-supplied ids. HEAD is
// allowed for the same preview-validation reason as /files/presigned. // allowed for the same preview-validation reason as /files/presigned.
"/api/v1/training/templates/signed-file": {"GET", "HEAD"}, "/api/v1/training/templates/signed-file": {"GET", "HEAD"},
// 企微扫码签到免登(2026-11 需求):学员在企微内置浏览器打开落地页时没有
// 平台会话,免登链路凭「未过期签到码 token(state)+ 一次性 OAuth code」
// 鉴权,路由级 IP 限流承担防滥用;checkin-page(登录态)不在此列。
"/api/v1/training/wecom/checkin-auth": {"GET"},
"/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.
+22 -1
View File
@@ -119,9 +119,30 @@ var publicAuthLimiter = newIPRateLimiter(
// through the project's AppError type so it flows through the same // through the project's AppError type so it flows through the same
// error middleware as the rest of the auth surface. // error middleware as the rest of the auth surface.
func PublicAuthRateLimit() gin.HandlerFunc { func PublicAuthRateLimit() gin.HandlerFunc {
return rateLimitWith(publicAuthLimiter)
}
// wecomCheckinRateLimitMax 培训扫码免登专用预算:教室场景几十名学员共享同一
// 办公网出口 IP,若复用 30/min 的共享 auth 限流,集中扫码会整批 429。签到
// 链路独立限流器放宽到 600/min/IP(百人级课堂在 5 分钟轮换窗口内仍宽裕),
// 同时保留对脚本刷 code/token 的约束。
const wecomCheckinRateLimitMax = 600
// wecomCheckinLimiter 独立桶,不与 share-link/auth 端点共享预算。
var wecomCheckinLimiter = newIPRateLimiter(publicAuthRateLimitWindow, wecomCheckinRateLimitMax)
// WecomCheckinRateLimit rate-limits the anonymous WeCom scan-checkin endpoints
// (checkin-auth / checkin-session) by client IP.
func WecomCheckinRateLimit() gin.HandlerFunc {
return rateLimitWith(wecomCheckinLimiter)
}
// rateLimitWith adapts an ipRateLimiter into Gin middleware; 429 flows through
// the project's AppError middleware like the rest of the auth surface.
func rateLimitWith(l *ipRateLimiter) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
ip := c.ClientIP() ip := c.ClientIP()
if !publicAuthLimiter.allow(ip) { if !l.allow(ip) {
c.Error(&apperrors.AppError{ c.Error(&apperrors.AppError{
Code: apperrors.ErrTooManyRequests, Code: apperrors.ErrTooManyRequests,
Message: "too many requests; please retry shortly", Message: "too many requests; please retry shortly",
+1 -1
View File
@@ -337,7 +337,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards) RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards) RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards) RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards)
RegisterOrgRoutes(v1, params.OrgCenterHandler, rbacGuards) RegisterOrgRoutes(v1, params.OrgCenterHandler, params.TrainingHandler, rbacGuards)
RegisterChunkerDebugRoutes(v1, rbacGuards) RegisterChunkerDebugRoutes(v1, rbacGuards)
// Fail fast if any declared API-key policy points at a route // Fail fast if any declared API-key policy points at a route
+24 -1
View File
@@ -2,6 +2,7 @@ package router
import ( import (
"academy/internal/handler/orgcenter" "academy/internal/handler/orgcenter"
"academy/internal/handler/training"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -11,7 +12,12 @@ import (
// - 空间 RBAC 把关:读 Viewer+,写 Contributor+; // - 空间 RBAC 把关:读 Viewer+,写 Contributor+;
// - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知; // - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知;
// - 不对 API Key 开放(组织数据面向登录用户,默认拒绝)。 // - 不对 API Key 开放(组织数据面向登录用户,默认拒绝)。
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards) { //
// th 为培训域 handler,可空:职称角色/企微账号维护自培训域迁入组织架构页后,
// /org 域提供同名写接口(直接复用培训 handler —— 其 requireRoles 基于
// callerTenantID 做角色细控,与 org 域租户口径一致,且不经培训域的
// TrainingTenantResolution 租户回落,跨空间 HR 在组织架构页操作不会错绑租户)。
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, th *training.Handler, g *rbacGuards) {
if h == nil { if h == nil {
return return
} }
@@ -28,6 +34,23 @@ func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards)
orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers) orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers)
orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees) orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees)
// ---- 归属空间收编(登录默认落点) ----
// Owner 限定:改的是账号级登录落点(users.tenant_id + 最近活跃租户偏好),
// 与成员批量导入/ Casdoor 同步同权限级别,组织架构页仅 Owner 可见入口。
orgGroup.GET("/employees/adoptable", g.Owner(), h.ListAdoptableUsers)
orgGroup.POST("/employees/adopt-home", g.Owner(), h.AdoptHomeTenant)
// ---- 职称角色 / 企微账号(培训域语义,handler 内 requireRoles(HR,经理) 细控) ----
// 职称角色页(培训 members 子页)迁入组织架构页后的 /org 域别名路由:
// 复用培训 handler,角色绑定仍写 module_key='training' 的 org_module_members。
if th != nil {
orgGroup.PUT("/employees/:id/roles", g.Contributor(), th.UpdateMemberRoles)
orgGroup.PUT("/employees/:id/wecom-userid", g.Contributor(), th.UpdateMemberWecomUserid)
// wecom-userid-sync 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式)。
orgGroup.POST("/employees/wecom-userid-sync/preview", g.Contributor(), th.SyncWecomUseridsPreview)
orgGroup.POST("/employees/wecom-userid-sync/apply", g.Contributor(), th.SyncWecomUseridsApply)
}
// ---- 模块角色绑定 ---- // ---- 模块角色绑定 ----
orgGroup.GET("/modules/:module_key/members", h.ListModuleMembers) orgGroup.GET("/modules/:module_key/members", h.ListModuleMembers)
orgGroup.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember) orgGroup.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember)
+23 -1
View File
@@ -4,6 +4,7 @@ import (
"strings" "strings"
"academy/internal/handler/training" "academy/internal/handler/training"
"academy/internal/middleware"
"academy/internal/utils" "academy/internal/utils"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -24,7 +25,20 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1 // trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。 // 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned) r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
trainingGroup := r.Group("/training", g.Viewer()) // 企微扫码签到免登(2026-11 需求):两个匿名入口直挂 v1(noAuthAPI 白名单 +
// 路由级 IP 限流),身份由签到码 token / OAuth code 承载,不走 Viewer 登录
// 守卫。限流用签到专用桶 WecomCheckinRateLimit(600/min/IP):教室几十人
// 共享一个出口 IP,共享 auth 限流(30/min)会整批 429。
r.GET("/training/wecom/checkin-auth", middleware.WecomCheckinRateLimit(), h.WecomCheckinAuth)
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):培训域数据空间按员工档案归属解析 ——
// 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在
// 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。
trainingGroup := r.Group("/training", g.Viewer(), h.TrainingTenantResolution())
{ {
// ---- 我的档案(角色决定工作台渲染) ---- // ---- 我的档案(角色决定工作台渲染) ----
trainingGroup.GET("/members/me", h.Me) trainingGroup.GET("/members/me", h.Me)
@@ -102,6 +116,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial) trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial)
// material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。 // material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。
trainingGroup.POST("/course-library/:id/material/from-kb", g.Contributor(), h.AttachCourseLibraryMaterialFromKb) 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) trainingGroup.GET("/course-library/:id/material/file", h.CourseLibraryMaterialFile)
// ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ---- // ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ----
trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks) trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks)
@@ -129,8 +145,12 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// ---- 签到域 ---- // ---- 签到域 ----
trainingGroup.POST("/sessions/:id/sign-code", g.Contributor(), h.CreateSignCode) trainingGroup.POST("/sessions/:id/sign-code", g.Contributor(), h.CreateSignCode)
// sessions/:id/sign-code GET 兼职惰性轮换触发器(2026-11:讲师页每 10s
// 轮询,超 rotation_sec 窗口自动轮换返回新码,旧码即时作废)。
trainingGroup.GET("/sessions/:id/sign-code", h.GetSignCode) trainingGroup.GET("/sessions/:id/sign-code", h.GetSignCode)
trainingGroup.POST("/sign-records/checkin", h.Checkin) trainingGroup.POST("/sign-records/checkin", h.Checkin)
// wecom/checkin-page 落地页数据(登录态;PC 讲师自测/企微内已有会话)。
trainingGroup.POST("/wecom/checkin-page", h.WecomCheckinPage)
trainingGroup.GET("/sessions/:id/sign-records", h.ListSignRecords) trainingGroup.GET("/sessions/:id/sign-records", h.ListSignRecords)
trainingGroup.POST("/sign-records/:id/review", g.Contributor(), h.ReviewSignRecord) trainingGroup.POST("/sign-records/:id/review", g.Contributor(), h.ReviewSignRecord)
trainingGroup.GET("/sessions/:id/sign-summary", h.SignSummary) trainingGroup.GET("/sessions/:id/sign-summary", h.SignSummary)
@@ -165,6 +185,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
trainingGroup.GET("/learning-progress", h.ListMyCourseProgress) trainingGroup.GET("/learning-progress", h.ListMyCourseProgress)
trainingGroup.GET("/learning-tasks", h.ListMyLearningTasks) trainingGroup.GET("/learning-tasks", h.ListMyLearningTasks)
trainingGroup.GET("/learning-tasks/all", h.ListCourseLearningTasks) trainingGroup.GET("/learning-tasks/all", h.ListCourseLearningTasks)
// my/enrolled-course-ids 我经场次学员名单报名的课程 id 集合(我的培训「我参加」判定)。
trainingGroup.GET("/my/enrolled-course-ids", h.ListMyEnrolledCourseIds)
trainingGroup.POST("/course-feedbacks", h.SaveFeedback) trainingGroup.POST("/course-feedbacks", h.SaveFeedback)
trainingGroup.POST("/course-feedbacks/:id/reply", g.Contributor(), h.ReplyFeedback) trainingGroup.POST("/course-feedbacks/:id/reply", g.Contributor(), h.ReplyFeedback)
trainingGroup.GET("/course-feedbacks/pending", h.ListPendingFeedbacks) trainingGroup.GET("/course-feedbacks/pending", h.ListPendingFeedbacks)
+7
View File
@@ -50,6 +50,13 @@ const (
// AuditActionInvitationExpired fires when the lazy sweep transitions // AuditActionInvitationExpired fires when the lazy sweep transitions
// an overdue pending row to expired. Actor is empty (system). // an overdue pending row to expired. Actor is empty (system).
AuditActionInvitationExpired AuditAction = "rbac.invitation_expired" AuditActionInvitationExpired AuditAction = "rbac.invitation_expired"
// AuditActionMemberHomeAdopted fires when a tenant Owner batch-adopts
// members' home tenants (users.tenant_id + LastActiveTenantID) into the
// operating workspace (组织架构「收编到本空间」). The membership rows are
// untouched — only the default-landing pointer moves — so this is
// distinct from member_added. Details payload carries
// {user_ids, adopted, skipped} for batch reconciliation.
AuditActionMemberHomeAdopted AuditAction = "rbac.member_home_adopted"
// VectorStore lifecycle actions. Emitted by VectorStoreService. // VectorStore lifecycle actions. Emitted by VectorStoreService.
// Cover both env-store-derived (__env_*) and DB store create / // Cover both env-store-derived (__env_*) and DB store create /
+16
View File
@@ -22,14 +22,21 @@ type OrgCenterRepository interface {
GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error) GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error)
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error) GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error
// InsertEmployeesIfAbsent 成员加入时自动入册:按 (tenant, user_id) 补建,
// 仅回填为空的工号/部门,不覆盖人工维护字段。
InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error
UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error
DeleteEmployee(ctx context.Context, tenantID uint64, id string) error DeleteEmployee(ctx context.Context, tenantID uint64, id string) error
CountEmployees(ctx context.Context, tenantID uint64) (int64, error) CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
// ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。 // ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。
ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error)
// GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。 // GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。
GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error) GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error)
// GetRosterUserInfos 指定成员的入册所需字段(平台账号 + 同步部门)。
GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error)
// ---- 模块角色绑定 ---- // ---- 模块角色绑定 ----
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error) GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
@@ -52,12 +59,21 @@ type OrgCenterService interface {
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error) GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
// ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。 // ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。
ImportEmployees(ctx context.Context, tenantID uint64, employees []*types.OrgEmployee) (int, error) ImportEmployees(ctx context.Context, tenantID uint64, employees []*types.OrgEmployee) (int, error)
// EnsureEmployeesForUsers 成员加入空间时自动入册:按平台账号补建员工档案,
// 部门按同步字段(dept_code 优先/dept_name 兜底)自动匹配;fail-open 不阻断入伙。
EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error
UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error)
CountEmployees(ctx context.Context, tenantID uint64) (int64, error) CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
// ListTenantUsers 平台用户列表(员工导入选择器数据源)。 // ListTenantUsers 平台用户列表(员工导入选择器数据源)。
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
// ListAdoptableUsers 归属空间不在本空间的活跃成员列表(收编预览)。
ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error)
// AdoptHomeTenant 批量收编:把指定成员的归属空间(登录默认落点)改为本空间。
// 仅收编本空间活跃成员,逐条跳过并回传原因;成功后补跑一次自动入册。
AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error)
// 模块角色绑定 // 模块角色绑定
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error) GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error) PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error)
@@ -17,4 +17,12 @@ type TenantBootstrapService interface {
// bootstrap knowledge base are skipped. ownerUserID (may be empty for // bootstrap knowledge base are skipped. ownerUserID (may be empty for
// platform-managed tenants) is recorded as the KB creator. // platform-managed tenants) is recorded as the KB creator.
SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string)
// EnsureTenantDefaultKnowledgeBases lazily self-heals a workspace's
// out-of-the-box defaults on list access: the two enterprise-training KBs
// are always ensured (Source-marker idempotent), and the starter KB is
// re-created only when the workspace has no knowledge bases at all (a
// seed that never succeeded). Idempotent and fail-open — safe to call on
// read paths. The execution tenant is taken from the context.
EnsureTenantDefaultKnowledgeBases(ctx context.Context)
} }
+96 -7
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
@@ -29,6 +40,26 @@ type TrainingListQuery struct {
Keyword string Keyword string
Page int Page int
PageSize int PageSize int
// 课程管理学员目录口径(000160,scope=catalog 时 handler 注入):
// CatalogOnly 仅返回已发布课程,且适合人员须覆盖调用方 ——
// suitable='全部' 或 =调用方部门名;未设置适合人员的存量课程沿用
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。
CatalogOnly bool
CatalogDeptID 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 培训域数据访问(按域分组的方法集合)。
@@ -42,6 +73,15 @@ type TrainingRepository interface {
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。 // 等场景高频只读);部门与名册管理走 OrgCenterRepository。
GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error) GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error)
GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error) GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
// GetMemberByWecomUserid 企微免登反查:按 org_employees.wecom_userid 定位
// 培训档案(扫码签到 code 换身份,2026-11 需求)。
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)的租户
// (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。
FindArchiveTenantID(ctx context.Context, userID string) (uint64, 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)
@@ -83,6 +123,11 @@ 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(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
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。 // UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
@@ -95,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
@@ -102,6 +150,11 @@ type TrainingRepository interface {
ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error) ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
// CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。 // CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。
CountEnrolledMembersByCourse(ctx context.Context, tenantID uint64) (map[string]int, error) CountEnrolledMembersByCourse(ctx context.Context, tenantID uint64) (map[string]int, error)
// CountEnrolledMembersByCourseID 单课程场次学员名单人数(发布必填校验,000161)。
CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error)
// ListMyEnrolledCourseIDs 当前成员经场次学员名单报名的课程 id 去重集合
// (我的培训「我参加」判定数据源;软删名单/软删场次不计)。
ListMyEnrolledCourseIDs(ctx context.Context, tenantID uint64, memberID string) ([]string, error)
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(课程管理列表学习/考试状态列)。 // CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(课程管理列表学习/考试状态列)。
CourseStudyStats(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error) CourseStudyStats(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error)
// CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。 // CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。
@@ -124,9 +177,14 @@ type TrainingRepository interface {
UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error
GetSignCodeBySession(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) GetSignCodeBySession(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error)
GetSignCodeByToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error) GetSignCodeByToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error)
// GetSignCodeByTokenGlobal 匿名扫码入口(checkin-auth/checkin-session)按 token
// 全局定位签到码,租户由码行反解;同时命中当前码与轮换宽限中的前码(prev_token)。
GetSignCodeByTokenGlobal(ctx context.Context, token string) (*types.TrainingSignCode, error)
UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error
GetSignRecord(ctx context.Context, tenantID uint64, sessionID, memberID string) (*types.TrainingSignRecord, error) GetSignRecord(ctx context.Context, tenantID uint64, sessionID, memberID string) (*types.TrainingSignRecord, error)
GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error) GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error)
// GetSignRecordByNonce 防重放:扫码签到 nonce 已用过则拒绝(2026-11 需求)。
GetSignRecordByNonce(ctx context.Context, tenantID uint64, nonce string) (*types.TrainingSignRecord, error)
ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error) ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error)
ReviewSignRecord(ctx context.Context, record *types.TrainingSignRecord) error ReviewSignRecord(ctx context.Context, record *types.TrainingSignRecord) error
SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error) SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error)
@@ -265,6 +323,9 @@ type TrainingService interface {
SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error) SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error)
// CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。 // CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。
CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error) CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
// ResolveTrainingTenant 企业培训数据空间解析(000160):当前空间有培训档案
// 用当前空间;否则回退到最早在职员工档案所在空间;都没有维持当前空间。
ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error)
// 计划域 // 计划域
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error) ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
@@ -272,7 +333,8 @@ type TrainingService interface {
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error) // ImportDemands 批量导入需求;返回导入行与自动新增的待核验课程数(000158)。
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(ctx context.Context, tenantID uint64, id string) error
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。 // ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
@@ -306,9 +368,10 @@ 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 非空时
@@ -320,11 +383,15 @@ type TrainingService interface {
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 移除课件条目(000164 多课件:mid 定位,空 =
// 最新一条;文件/知识库挂接随条目移除,名称登记保留)。
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)
@@ -346,14 +413,33 @@ type TrainingService interface {
// 签到域 // 签到域
CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error) CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error)
// GetSignCode 取场次当前签到码;超过轮换窗口(rotation_sec,默认 5 分钟)时
// 惰性轮换:旧 token 挪入 prev,新码即时生效(2026-11 企微扫码需求)。
GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error)
Checkin(ctx context.Context, tenantID uint64, userID, token string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) // Checkin 学员扫码签到(带定位校验);in.EmployeeNo 非空时启用严格校验:
// 工号须与档案一致且在「参加人员」名单中,名单外直接拒绝(2026-11 需求)。
Checkin(ctx context.Context, tenantID uint64, userID string, in *types.CheckinInput) (*types.TrainingSignRecord, error)
// CheckinFor 文员代扫码/补录:以目标成员身份签到(proxy 标记留痕)。 // CheckinFor 文员代扫码/补录:以目标成员身份签到(proxy 标记留痕)。
CheckinFor(ctx context.Context, tenantID uint64, operatorUserID, token, targetMemberID string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) CheckinFor(ctx context.Context, tenantID uint64, operatorUserID, token, targetMemberID string, lat, lng float64, channel string) (*types.TrainingSignRecord, error)
ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error) ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error)
ReviewSignRecord(ctx context.Context, tenantID uint64, recordID, decision, operatorID string) (*types.TrainingSignRecord, error) ReviewSignRecord(ctx context.Context, tenantID uint64, recordID, decision, operatorID string) (*types.TrainingSignRecord, error)
SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error) SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error)
ExportEvidence(ctx context.Context, tenantID uint64, sessionIDs []string) (filename string, data []byte, err error) ExportEvidence(ctx context.Context, tenantID uint64, sessionIDs []string) (filename string, data []byte, err error)
// ---- 企微扫码签到免登(2026-11 需求) ----
// WecomCheckinAuthURL 按签到码 token 生成企微网页授权链接(snsapi_base 静默)。
WecomCheckinAuthURL(ctx context.Context, token, redirectURI string) (string, error)
// WecomCheckinSession OAuth code 换身份:反查 wecom_userid 绑定、签发平台
// JWT(签到即自动登录)并一次带回落地页数据。
WecomCheckinSession(ctx context.Context, code, state string) (*types.WecomCheckinSession, error)
// WecomCheckinPage 已登录用户(PC 自测)取落地页数据。
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 落对象存储。
@@ -426,6 +512,9 @@ type TrainingService interface {
// ListMyCourseProgress 当前用户在某课程下各课件的学习进度(学习详情页回读)。 // ListMyCourseProgress 当前用户在某课程下各课件的学习进度(学习详情页回读)。
ListMyCourseProgress(ctx context.Context, tenantID uint64, userID, courseID string) ([]*types.TrainingLearningProgress, error) ListMyCourseProgress(ctx context.Context, tenantID uint64, userID, courseID string) ([]*types.TrainingLearningProgress, error)
ListMyLearningTasks(ctx context.Context, tenantID uint64, userID string) ([]*types.TrainingLearningTask, error) ListMyLearningTasks(ctx context.Context, tenantID uint64, userID string) ([]*types.TrainingLearningTask, error)
// ListMyEnrolledCourseIDs 我经场次学员名单报名的课程 id 去重集合(我的培训
// 「我参加」判定,与学习任务/讲师/部门范围口径互补;线下课参加人员由此可见)。
ListMyEnrolledCourseIDs(ctx context.Context, tenantID uint64, userID string) ([]string, error)
// ListCourseLearningTasks 按课程返回全员学习任务(人事/讲师课程学习情况)。 // ListCourseLearningTasks 按课程返回全员学习任务(人事/讲师课程学习情况)。
ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error) ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error)
SaveFeedback(ctx context.Context, tenantID uint64, userID, sessionID string, rating int, comment string) (*types.TrainingCourseFeedback, error) SaveFeedback(ctx context.Context, tenantID uint64, userID, sessionID string, rating int, comment string) (*types.TrainingCourseFeedback, error)
+6
View File
@@ -51,6 +51,12 @@ type UserService interface {
ValidatePassword(ctx context.Context, userID string, password string) error ValidatePassword(ctx context.Context, userID string, password string) error
// GenerateTokens generates access and refresh tokens for user // GenerateTokens generates access and refresh tokens for user
GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error) GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error)
// SessionResponseForUser assembles a full login response (token pair +
// active tenant + memberships) for an already authenticated identity,
// honouring the same login tenant resolution as /auth/login. Used by the
// WeCom scan-checkin silent-login path so the browser persists the
// session exactly like a normal login (2026-11 需求).
SessionResponseForUser(ctx context.Context, user *types.User) (*types.LoginResponse, error)
// BuildLoginMemberships projects the user's tenant memberships into // BuildLoginMemberships projects the user's tenant memberships into
// the login-response shape. activeTenant is reused (without an extra // the login-response shape. activeTenant is reused (without an extra
// lookup) for the matching row's TenantName. The slice is guaranteed // lookup) for the matching row's TenantName. The slice is guaranteed
+55 -27
View File
@@ -23,14 +23,14 @@ const (
// OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。 // OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。
type OrgDept struct { type OrgDept struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"` ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"` TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"` ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"`
Name string `json:"name" gorm:"type:varchar(128);not null"` Name string `json:"name" gorm:"type:varchar(128);not null"`
Code string `json:"code" gorm:"type:varchar(64);default:''"` Code string `json:"code" gorm:"type:varchar(64);default:''"`
Sort int `json:"sort" gorm:"default:0"` Sort int `json:"sort" gorm:"default:0"`
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"`
} }
@@ -39,17 +39,17 @@ func (OrgDept) TableName() string { return "org_depts" }
// OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。 // OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。
type OrgEmployee struct { type OrgEmployee struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"` ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"` TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"`
UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"` UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"`
EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"` EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"` DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"`
Post string `json:"post" gorm:"type:varchar(128);default:''"` Post string `json:"post" gorm:"type:varchar(128);default:''"`
LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"` LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"`
WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"` WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"`
Status string `json:"status" gorm:"type:varchar(16);default:'active'"` Status string `json:"status" gorm:"type:varchar(16);default:'active'"`
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"`
// 联查只读展示字段(不落库): // 联查只读展示字段(不落库):
@@ -76,14 +76,14 @@ func (m *OrgEmployee) OrgRoleList() []string {
// OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。 // OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。
type OrgModuleMember struct { type OrgModuleMember struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"` ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"` TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"`
ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"` ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"`
EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"` EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"`
Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"` Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"`
Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"` Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"`
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"`
} }
@@ -97,3 +97,31 @@ type OrgListQuery struct {
Page int Page int
PageSize int PageSize int
} }
// OrgAdoptableUser 可收编成员(归属空间不在本空间的活跃成员),「收编到本空间」
// 预览行。归属空间(users.tenant_id)决定登录/refresh 默认进入的工作区;员工
// 首登自动开通个人空间(create_personal 默认)后归属指针停在个人空间,收编把
// 该指针改指本空间——成员关系、角色与个人空间数据均不变,非破坏性。
type OrgAdoptableUser struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
HomeTenantID uint64 `json:"home_tenant_id"`
HomeTenantName string `json:"home_tenant_name"`
InRoster bool `json:"in_roster"`
}
// OrgAdoptSkip 批量收编中单条跳过记录(逐条原因回传 UI 展示)。
type OrgAdoptSkip struct {
UserID string `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Reason string `json:"reason"`
}
// OrgAdoptResult 批量收编结果统计。
type OrgAdoptResult struct {
Adopted int `json:"adopted"`
Skipped []*OrgAdoptSkip `json:"skipped"`
}
+178 -19
View File
@@ -363,16 +363,20 @@ type TrainingDemand struct {
TenantID uint64 `json:"tenant_id" gorm:"not null;index"` TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Year int `json:"year" gorm:"not null;index"` Year int `json:"year" gorm:"not null;index"`
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。 // Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
Code string `json:"code" gorm:"type:varchar(32);default:''"` Code string `json:"code" gorm:"type:varchar(32);default:''"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"` DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"` SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"` CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
Plant string `json:"plant" gorm:"type:varchar(64);default:''"` // LibraryCourseID 需求所填课程自动匹配的课程管理条目 id(000158):填报/导入时
Category string `json:"category" gorm:"type:varchar(32);default:''"` // 按课程名称精准查找,命中回填;未命中自动新增该课程(待核验)后回填,确认转
SessionCount int `json:"session_count" gorm:"default:1"` // 月培训计划时据此关联(存量数据无值时回退同名扫描兜底)。
Location string `json:"location" gorm:"type:varchar(128);default:''"` LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"` Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"` Category string `json:"category" gorm:"type:varchar(32);default:''"`
SessionCount int `json:"session_count" gorm:"default:1"`
Location string `json:"location" gorm:"type:varchar(128);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。 // LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"` LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。 // TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
@@ -541,6 +545,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)。
@@ -576,6 +585,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 {
@@ -591,8 +613,17 @@ type TrainingCourseLibrary struct {
OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"` OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"`
// Description 说明。 // Description 说明。
Description string `json:"description" gorm:"type:text;default:''"` Description string `json:"description" gorm:"type:text;default:''"`
// SuitableMembers 适合人员(对应需求表「参加人员」,自由文本,如:财会人员)。 // SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(255);default:''"` // (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
// 000163 起语义升级为「课程权限」展示文本(部门名+人员名),精确匹配走
// perm_dept_ids/perm_user_ids 两列,本列保留存量兼容与导出展示。
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:''"`
// 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 选修课)。
@@ -613,7 +644,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'"`
@@ -632,6 +667,8 @@ type TrainingCourseLibrary struct {
LecturerName string `json:"lecturer_name" gorm:"->"` LecturerName string `json:"lecturer_name" gorm:"->"`
// CreatorName 创建人姓名(联查 users 只读,不落库;列表「创建人」列展示)。 // CreatorName 创建人姓名(联查 users 只读,不落库;列表「创建人」列展示)。
CreatorName string `json:"creator_name" gorm:"->"` CreatorName string `json:"creator_name" gorm:"->"`
// QuestionBankCount 关联题库数(联查只读,不落库;列表「试题」有/无展示)。
QuestionBankCount int `json:"question_bank_count" gorm:"->"`
// OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。 // OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。
OwnerDeptName string `json:"owner_dept_name" gorm:"->"` OwnerDeptName string `json:"owner_dept_name" gorm:"->"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
@@ -642,6 +679,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 已签到成员(线下参与)。
@@ -742,13 +832,18 @@ type TrainingSignCode struct {
SessionID string `json:"session_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_sign_codes_session"` SessionID string `json:"session_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_sign_codes_session"`
Token string `json:"token" gorm:"type:varchar(64);not null;uniqueIndex:uq_tr_sign_codes_token"` Token string `json:"token" gorm:"type:varchar(64);not null;uniqueIndex:uq_tr_sign_codes_token"`
ExpireAt *time.Time `json:"expire_at"` ExpireAt *time.Time `json:"expire_at"`
GeoLat float64 `json:"geo_lat" gorm:"default:0"` // PrevToken/PrevExpireAt 轮换宽限(2026-11 需求:二维码每 5 分钟自动轮换,
GeoLng float64 `json:"geo_lng" gorm:"default:0"` // 旧码即时作废;宽限期内(prev_expire_at + rotation_grace_sec)仍可签到,
GeoRadius int `json:"geo_radius" gorm:"default:0"` // 防"扫码即轮换"踩空。零值 = 无前码,严格作废。
CreatedBy string `json:"created_by" gorm:"type:varchar(36);default:''"` PrevToken string `json:"prev_token" gorm:"type:varchar(64);default:''"`
CreatedAt time.Time `json:"created_at"` PrevExpireAt *time.Time `json:"prev_expire_at"`
UpdatedAt time.Time `json:"updated_at"` GeoLat float64 `json:"geo_lat" gorm:"default:0"`
DeletedAt *time.Time `json:"-" gorm:"index"` GeoLng float64 `json:"geo_lng" gorm:"default:0"`
GeoRadius int `json:"geo_radius" gorm:"default:0"`
CreatedBy string `json:"created_by" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
} }
// TableName pins the physical table name. // TableName pins the physical table name.
@@ -766,6 +861,8 @@ type TrainingSignRecord struct {
Lng float64 `json:"lng" gorm:"default:0"` Lng float64 `json:"lng" gorm:"default:0"`
DistanceM float64 `json:"distance_m" gorm:"default:0"` DistanceM float64 `json:"distance_m" gorm:"default:0"`
Status string `json:"status" gorm:"type:varchar(16);default:'normal';index"` Status string `json:"status" gorm:"type:varchar(16);default:'normal';index"`
// Nonce 扫码签到随机时间戳(防重放留痕;同 nonce 二次提交直接拒绝,2026-11 需求)。
Nonce string `json:"nonce" gorm:"type:varchar(64);default:''"`
AbnormalFlags JSON `json:"abnormal_flags" gorm:"type:jsonb;default:'[]'"` AbnormalFlags JSON `json:"abnormal_flags" gorm:"type:jsonb;default:'[]'"`
ReviewedBy string `json:"reviewed_by" gorm:"type:varchar(36);default:''"` ReviewedBy string `json:"reviewed_by" gorm:"type:varchar(36);default:''"`
ReviewedAt *time.Time `json:"reviewed_at"` ReviewedAt *time.Time `json:"reviewed_at"`
@@ -777,6 +874,68 @@ type TrainingSignRecord struct {
// TableName pins the physical table name. // TableName pins the physical table name.
func (TrainingSignRecord) TableName() string { return "tr_sign_records" } func (TrainingSignRecord) TableName() string { return "tr_sign_records" }
// CheckinInput 学员本人扫码签到入参(2026-11 企微扫码免登需求;代录仍走
// CheckinFor,不受这些严格校验约束)。
type CheckinInput struct {
Token string `json:"token"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
Channel string `json:"channel"`
// EmployeeNo 录入工号:非空时启用严格校验 —— 必须与登录账号档案工号一致,
// 且必须在该场次「参加人员」名单中(名单外直接拒绝,不再仅标记待复核)。
EmployeeNo string `json:"employee_no"`
// Nonce 随机时间戳(前端生成 Date.now()+随机段):同 nonce 二次提交拒绝(防重放)。
Nonce string `json:"nonce"`
// ClientTS 客户端提交时刻(毫秒):>0 时校验与服务器时钟偏差(clock_skew_sec)。
ClientTS int64 `json:"client_ts"`
}
// WecomCheckinCourse 企微扫码签到落地页的课程/场次摘要(补充需求 1:签到页展示课程信息)。
type WecomCheckinCourse struct {
CourseID string `json:"course_id"`
CourseName string `json:"course_name"`
LecturerName string `json:"lecturer_name"`
StartAt *time.Time `json:"start_at"`
EndAt *time.Time `json:"end_at"`
Location string `json:"location"`
Status string `json:"status"`
// CanSignToday 是否培训当天(非当天前端置灰签到按钮并提示,后端仍强校验兜底)。
CanSignToday bool `json:"can_sign_today"`
}
// WecomCheckinPage 企微扫码签到落地页数据:免登(code 换会话)与已登录 PC 自测
// 两条路径共用同一份页面载荷。
type WecomCheckinPage struct {
Member *OrgEmployee `json:"member,omitempty"` // 工号/姓名确认行
Course *WecomCheckinCourse `json:"course,omitempty"`
// CourseID 课程详情页跳转(签到成功后自动进入,2026-11 需求补充 3)。
CourseID string `json:"course_id"`
// SessionID 场次 id(签到接口定位/排查用)。
SessionID string `json:"session_id"`
// SignExpireAt 当前签到码有效期:落地页倒计时数据源(补充需求 2)。
SignExpireAt *time.Time `json:"sign_expire_at"`
InRoster bool `json:"in_roster"`
AlreadySigned bool `json:"already_signed"`
}
// WecomCheckinSession 企微 OAuth code 换会话响应:内嵌 LoginResponse(token/
// refresh_token/user/active_tenant/memberships),前端与 /auth/login 同构持久化,
// 即"签到即自动登录";并携带落地页数据一次返回。
type WecomCheckinSession struct {
LoginResponse
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"
+4
View File
@@ -308,6 +308,9 @@ type UserInfo struct {
Username string `json:"username" extensions:"x-agent"` Username string `json:"username" extensions:"x-agent"`
Email string `json:"email" extensions:"x-agent"` Email string `json:"email" extensions:"x-agent"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
// DisplayName 姓名/显示名。工号式 IdP 的 username 是工号,前端左下角等
// 位置展示姓名用;随 /auth/me、登录等返回 UserInfo 的接口一并下发。
DisplayName string `json:"display_name"`
TenantID uint64 `json:"tenant_id" extensions:"x-agent"` TenantID uint64 `json:"tenant_id" extensions:"x-agent"`
IsActive bool `json:"is_active" extensions:"x-agent"` IsActive bool `json:"is_active" extensions:"x-agent"`
CanAccessAllTenants bool `json:"can_access_all_tenants"` CanAccessAllTenants bool `json:"can_access_all_tenants"`
@@ -324,6 +327,7 @@ func (u *User) ToUserInfo() *UserInfo {
Username: u.Username, Username: u.Username,
Email: u.Email, Email: u.Email,
Avatar: u.Avatar, Avatar: u.Avatar,
DisplayName: u.DisplayName,
TenantID: u.TenantID, TenantID: u.TenantID,
IsActive: u.IsActive, IsActive: u.IsActive,
CanAccessAllTenants: u.CanAccessAllTenants, CanAccessAllTenants: u.CanAccessAllTenants,
@@ -0,0 +1,6 @@
-- Migration: 000158_demand_library_course (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Dropping tr_demands.library_course_id column...'; END $$;
ALTER TABLE tr_demands
DROP COLUMN IF EXISTS library_course_id;
@@ -0,0 +1,11 @@
-- Migration: 000158_demand_library_course
-- 年度需求(tr_demands)增加所填课程的课程管理关联:填报/导入时按课程名称在
-- 课程管理精准查找,命中自动关联;未命中自动新增该课程(待核验,000157 流转),
-- 经理核验课程并确认需求自动转月培训计划后,发布课程前校验已签核完成。
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Adding tr_demands.library_course_id column...'; END $$;
ALTER TABLE tr_demands
ADD COLUMN IF NOT EXISTS library_course_id VARCHAR(36) NOT NULL DEFAULT '';
COMMENT ON COLUMN tr_demands.library_course_id IS 'Course library item id auto-matched by exact course name on demand save/import (000158); auto-created as verify-pending when not found';
@@ -0,0 +1,6 @@
-- Migration: 000159_suitable_members_width (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Restoring tr_course_library.suitable_members to VARCHAR(255)...'; END $$;
ALTER TABLE tr_course_library
ALTER COLUMN suitable_members TYPE VARCHAR(255);
@@ -0,0 +1,11 @@
-- Migration: 000159_suitable_members_width
-- 「适合人员」改为部门多选口径(000159):存储归属部门名(「、」分隔,支持多选)
-- 或「全部」;单值/自由文本存量保持兼容(逗号/分号在匹配时归一)。拓宽列宽以
-- 容纳多部门名称拼接。
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Widening tr_course_library.suitable_members to VARCHAR(512)...'; END $$;
ALTER TABLE tr_course_library
ALTER COLUMN suitable_members TYPE VARCHAR(512);
COMMENT ON COLUMN tr_course_library.suitable_members IS 'Suitable audience dept names joined by ''、'' (multi-select), or ''全部'' for all; legacy free text kept, delimiters normalized on matching';
@@ -0,0 +1,10 @@
-- Migration: 000160_tenant_seq_reserve_builtin_host (down)
-- 回滚到旧行为:序列回到 10000(与 000000 初始迁移一致)。仅当真实租户
-- 尚未占用 10000 时执行,否则保留现值(占用的 id 无法安全腾挪)。
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM tenants WHERE id = 10000) THEN
PERFORM setval('tenants_id_seq', 10000, false);
END IF;
END $$;
@@ -0,0 +1,16 @@
-- Migration: 000160_tenant_seq_reserve_builtin_host
-- 租户序列与内置模型宿主租户(10000)避让。000000 初始迁移把 tenants_id_seq
-- 起点设为 10000,导致全新环境的第一个用户空间恰好占住保留的内置模型宿主
-- 租户 id(DefaultBuiltinModelTenantID=10000):SeedTenantDefaults 对该 id
-- 永不 seed(首用户空间没有任何默认库),且内置模型行(tenant_id=10000)
-- 的归属被真实空间占住。本迁移把序列推到 10001 之后:
-- 全新库(无租户行)→ 下一个租户 id 从 10001 开始,10000 永久保留;
-- 存量库 → 按现有 max(id) 连续续号,不受影响。
DO $$ BEGIN RAISE NOTICE '[Migration 000160] Realigning tenants_id_seq past reserved builtin-model host id 10000...'; END $$;
SELECT setval(
'tenants_id_seq',
GREATEST(COALESCE((SELECT MAX(id) FROM tenants), 0), 10001),
COALESCE((SELECT MAX(id) FROM tenants) IS NOT NULL, false)
);
@@ -0,0 +1,6 @@
-- Migration: 000161_org_roster_backfill (down)
-- 数据回填不可逆:回填行与此前人工/导入维护的员工档案无法区分(仅补空语义
-- 下老档案也可能被回填工号/部门),回滚不做删除,保留数据。
-- 如确需清理,请按 created_at 与迁移执行时间自行定位处理。
DO $$ BEGIN RAISE NOTICE '[Migration 000161] down is a no-op (backfilled roster rows are kept).'; END $$;
@@ -0,0 +1,58 @@
-- Migration: 000161_org_roster_backfill
-- 存量平台成员一次性自动补入「组织架构」员工名册(需求:平台新增成员自动
-- 添加到组织架构并自动匹配对应部门)。此后新加入空间的成员由
-- tenantMemberService 的 ensureOrgRoster 挂钩实时入册(service/orgcenter.go
-- EnsureEmployeesForUsers),本迁移负责把迁移前就已加入空间的存量成员补齐:
-- - 工号 employee_no = 平台账号 users.username(与导入回填同约定);
-- - 部门按 Casdoor 同步字段自动匹配:users.dept_code 命中 org_depts.code
-- 优先,dept_name 命中 org_depts.name 兜底(小写去空格,各自 LATERAL 取
-- sort/created_at 序首行);匹配不到已维护部门时 dept_id 留空,由管理员
-- 在组织架构页手动调整;
-- - ON CONFLICT (tenant_id, user_id) DO NOTHING:已有档案(含软删行)一律
-- 不动,不覆盖任何人工/OA 同步字段,迁移幂等可重放。
DO $$ BEGIN RAISE NOTICE '[Migration 000161] Backfilling org_employees for existing tenant members...'; END $$;
INSERT INTO org_employees
(id, tenant_id, user_id, employee_no, dept_id, post, lecturer_rate, wecom_userid, status, created_at, updated_at)
SELECT
gen_random_uuid()::text,
tm.tenant_id,
tm.user_id,
u.username,
COALESCE(dc.id, dn.id, ''),
'',
0,
'',
'active',
NOW(),
NOW()
FROM tenant_members tm
JOIN users u
ON u.id = tm.user_id
AND u.is_active = TRUE
AND u.deleted_at IS NULL
-- 部门编号精确命中优先(dept_code 同步自 IdP,与 syncDepts 匹配口径一致)
LEFT JOIN LATERAL (
SELECT d.id
FROM org_depts d
WHERE d.tenant_id = tm.tenant_id
AND d.deleted_at IS NULL
AND d.code <> ''
AND lower(btrim(d.code)) = lower(btrim(u.dept_code))
ORDER BY d.sort ASC, d.created_at ASC
LIMIT 1
) dc ON u.dept_code <> ''
-- 名称兜底:仅在编号未命中时参与,避免同名的编号部门抢占
LEFT JOIN LATERAL (
SELECT d.id
FROM org_depts d
WHERE d.tenant_id = tm.tenant_id
AND d.deleted_at IS NULL
AND lower(btrim(d.name)) = lower(btrim(u.dept_name))
ORDER BY d.sort ASC, d.created_at ASC
LIMIT 1
) dn ON u.dept_name <> '' AND dc.id IS NULL
WHERE tm.status = 'active'
AND tm.deleted_at IS NULL
ON CONFLICT (tenant_id, user_id) DO NOTHING;
@@ -0,0 +1,9 @@
-- Migration: 000162_training_sign_rotation (down)
-- 回滚轮换/防重放列;签到流水 nonce 列一并移除(留痕数据随列删除)。
ALTER TABLE tr_sign_codes
DROP COLUMN IF EXISTS prev_token,
DROP COLUMN IF EXISTS prev_expire_at;
ALTER TABLE tr_sign_records
DROP COLUMN IF EXISTS nonce;
@@ -0,0 +1,17 @@
-- Migration: 000162_training_sign_rotation
-- 企微扫码签到免登 + 二维码 5 分钟轮换(2026-11 需求):
-- 1. tr_sign_codes 增 prev_token / prev_expire_at:轮换时旧 token 挪入前码位,
-- 宽限期内(rotation_grace_sec,默认 30s)仍可签到,防"扫码即轮换"踩空;
-- upsert 覆盖后旧 token 即刻退出当前码位(GetSignCodeByToken 不再命中)。
-- 2. tr_sign_records 增 nonce:扫码签到随机时间戳防重放留痕,同 nonce 二次
-- 提交直接拒绝;历史行默认空串,不参与查重(空 nonce 不查)。
-- 全部 ADD COLUMN IF NOT EXISTS,迁移幂等可重放。
DO $$ BEGIN RAISE NOTICE '[Migration 000162] Adding sign-code rotation / sign-record nonce columns...'; END $$;
ALTER TABLE tr_sign_codes
ADD COLUMN IF NOT EXISTS prev_token VARCHAR(64) NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS prev_expire_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE tr_sign_records
ADD COLUMN IF NOT EXISTS nonce VARCHAR(64) NOT NULL DEFAULT '';
@@ -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;
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more