Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f43fbef5db | ||
|
|
9950a28346 | ||
|
|
ea0524c445 | ||
|
|
11450bdb96 | ||
|
|
448fbcdaff | ||
|
|
8f225ecea9 | ||
|
|
196478114c | ||
|
|
42042ca8bd | ||
|
|
7e1e670f0a | ||
|
|
8bd02e7c7e | ||
|
|
4112de0703 | ||
|
|
6594f97e3c | ||
|
|
0819f8c4d1 | ||
|
|
3c8b595064 | ||
|
|
11ce1c3c0c |
No files matched your search
@@ -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: |
|
||||||
|
|||||||
@@ -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
@@ -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
@@ -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) |
|
||||||
@@ -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,277 @@
|
|||||||
|
# 企微扫码签到免登 · 落地方案
|
||||||
|
|
||||||
|
> 状态:**已实施(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;然后测试环境走通全链路再复制到正式。
|
||||||
+1
-1
@@ -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">
|
||||||
|
|||||||
@@ -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 () => {
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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) =>
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -472,6 +474,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
|
||||||
}
|
}
|
||||||
@@ -524,6 +528,12 @@ export const attachCourseLibraryMaterialFromKb = (id: string, payload: { knowled
|
|||||||
export const downloadCourseLibraryMaterial = (id: string) =>
|
export const downloadCourseLibraryMaterial = (id: string) =>
|
||||||
getDown(`${base}/course-library/${enc(id)}/material/file`)
|
getDown(`${base}/course-library/${enc(id)}/material/file`)
|
||||||
|
|
||||||
|
/** 移除课件原始文件/知识库挂接(名称登记保留;课件变更即回待核验)。 */
|
||||||
|
export const removeCourseLibraryMaterial = (id: string) =>
|
||||||
|
post<{ success: boolean; data: TrainingLibraryCourse }>(
|
||||||
|
`${base}/course-library/${enc(id)}/material/remove`,
|
||||||
|
)
|
||||||
|
|
||||||
export const listSessions = (query?: ListQuery) =>
|
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 +647,69 @@ 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 })
|
||||||
|
|
||||||
|
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 +1034,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 +1380,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 同口径)。 */
|
||||||
|
|||||||
@@ -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()
|
||||||
})
|
})
|
||||||
|
|
||||||
// 切换菜单显示
|
// 切换菜单显示
|
||||||
|
|||||||
@@ -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%);
|
||||||
|
|||||||
@@ -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));
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -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駆動のエンタープライズアーキテクチャアップグレード',
|
||||||
|
|||||||
@@ -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 기반 엔터프라이즈 아키텍처 업그레이드',
|
||||||
|
|||||||
@@ -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-база знаний — корпоративная архитектура нового уровня на базе ИИ',
|
||||||
|
|||||||
@@ -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驱动的企业架构升级',
|
||||||
|
|||||||
@@ -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驅動的企業架構升級',
|
||||||
|
|||||||
@@ -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",
|
||||||
@@ -94,7 +96,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 +158,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",
|
||||||
@@ -177,11 +185,14 @@ const router = createRouter({
|
|||||||
meta: { requiresInit: true, requiresAuth: true }
|
meta: { requiresInit: true, requiresAuth: true }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// 学员扫码签到页:培训签到页二维码落地页,携 token 自动定位并签到(需登录态)。
|
// 学员扫码签到落地页(2026-11 企微扫码免登):企微「扫一扫」直接打开,
|
||||||
|
// 页面内自行完成免登(OAuth 静默授权)/自动登录/倒计时/点击签到,
|
||||||
|
// 故显式 requiresAuth:false + requiresInit:false 放行路由守卫
|
||||||
|
// (meta 缺省 = undefined 时守卫仍按需登录拦截,必须显式 false)。
|
||||||
path: "training/checkin/:token",
|
path: "training/checkin/:token",
|
||||||
name: "trainingCheckin",
|
name: "trainingCheckin",
|
||||||
component: () => import("../views/training/CheckinPage.vue"),
|
component: () => import("../views/training/CheckinPage.vue"),
|
||||||
meta: { requiresInit: true, requiresAuth: true }
|
meta: { requiresInit: false, requiresAuth: false }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// 组织架构:租户级共享组织架构(部门 + 员工档案),
|
// 组织架构:租户级共享组织架构(部门 + 员工档案),
|
||||||
@@ -368,7 +379,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 +388,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 +442,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 +452,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -165,9 +165,9 @@ export const TRAINING_MOCK = {
|
|||||||
|
|
||||||
// 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致)
|
// 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致)
|
||||||
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: '新入职员工', category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '入职通识手册.pptx', file_size: 839680, knowledge_id: 'kb-lib1', question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) },
|
||||||
{ id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '', 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: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '安全操作规程.docx', file_size: 512000, question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) },
|
||||||
{ id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, 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: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, question_bank_count: 0, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) },
|
||||||
]
|
]
|
||||||
|
|
||||||
// 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####)
|
// 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####)
|
||||||
@@ -313,6 +313,26 @@ 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 })
|
||||||
}
|
}
|
||||||
|
// 课件管理抽屉:上传/知识库挂接/移除回显对应课程条目并模拟文件字段变更
|
||||||
|
if (url.includes('/course-library/') && url.includes('/material/remove')) {
|
||||||
|
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
|
||||||
|
if (course) {
|
||||||
|
course.file_name = ''
|
||||||
|
course.file_size = 0
|
||||||
|
course.knowledge_id = ''
|
||||||
|
course.verify_status = 'pending'
|
||||||
|
}
|
||||||
|
return ok(course || { id: `c-new-${Date.now()}` })
|
||||||
|
}
|
||||||
|
if (url.includes('/course-library/') && url.includes('/material')) {
|
||||||
|
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
|
||||||
|
if (course) {
|
||||||
|
course.file_name = '预览课件.pdf'
|
||||||
|
course.file_size = 1024 * 820
|
||||||
|
course.verify_status = 'pending'
|
||||||
|
}
|
||||||
|
return ok(course || { id: `c-new-${Date.now()}` })
|
||||||
|
}
|
||||||
if (url.includes('/course-library/') && url.includes('/question-banks/import')) {
|
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 })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 = [];
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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')
|
||||||
|
|||||||
@@ -34,7 +34,32 @@
|
|||||||
<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>
|
||||||
@@ -46,6 +71,12 @@
|
|||||||
</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,6 +85,8 @@
|
|||||||
<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>
|
||||||
@@ -150,6 +183,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 +290,48 @@
|
|||||||
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'
|
||||||
|
|
||||||
|
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,6 +348,174 @@ 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' })
|
||||||
|
|
||||||
|
// ---- 职称角色 / 企微账号(自培训域「职称角色」页迁入) ----
|
||||||
|
|
||||||
|
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
|
||||||
|
const roleDict = ref<TrainingRoleDef[]>([])
|
||||||
|
// 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护)
|
||||||
|
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 openAdopt = async () => {
|
||||||
|
adoptVisible.value = true
|
||||||
|
adoptLoaded.value = false
|
||||||
|
adoptList.value = []
|
||||||
|
try {
|
||||||
|
const res = await listAdoptableUsers()
|
||||||
|
adoptList.value = unwrap(res) || []
|
||||||
|
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 = [
|
const deptColumns = [
|
||||||
{ colKey: 'name', title: '部门名称' },
|
{ colKey: 'name', title: '部门名称' },
|
||||||
{ colKey: 'code', title: '编码', width: 140 },
|
{ colKey: 'code', title: '编码', width: 140 },
|
||||||
@@ -200,15 +523,18 @@ const deptColumns = [
|
|||||||
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const employeeColumns = [
|
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
|
||||||
|
const employeeColumns = computed(() => [
|
||||||
{ colKey: 'employee_no', title: '工号', width: 90 },
|
{ colKey: 'employee_no', title: '工号', width: 90 },
|
||||||
{ colKey: 'user_name', title: '姓名' },
|
{ colKey: 'user_name', title: '姓名', width: 110 },
|
||||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
{ colKey: 'dept_name', title: '部门', width: 100 },
|
||||||
{ colKey: 'post', title: '岗位', width: 140 },
|
{ colKey: 'post', title: '岗位', width: 120 },
|
||||||
{ colKey: 'status', title: '状态', width: 76 },
|
{ colKey: 'wecom_userid', title: '企微账号', width: 110 },
|
||||||
// 列总宽超出面板宽度时固定在右侧,避免"修改"按钮被横向滚动挤出可视区
|
{ colKey: 'roles', title: '职称角色' },
|
||||||
{ colKey: 'op', title: '操作', width: 84, fixed: 'right' },
|
{ 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。
|
||||||
@@ -249,23 +575,53 @@ 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)
|
||||||
|
})
|
||||||
|
|
||||||
|
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 +705,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 +741,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 +786,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 +794,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>
|
||||||
@@ -498,4 +860,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>
|
||||||
@@ -1,19 +1,21 @@
|
|||||||
<template>
|
<template>
|
||||||
<!-- 学员扫码签到落地页:培训签到页二维码 → 企微/相机扫码直达,自动定位并提交签到 -->
|
<!-- 学员扫码签到落地页(2026-11 企微扫码免登需求):
|
||||||
|
企微「扫一扫」→ 静默免登(自动登录)→ 课程信息 + 签到倒计时 → 点击签到
|
||||||
|
→ 成功后自动进入该课程详情页。非企微环境提示改用企微扫码。 -->
|
||||||
<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 +30,271 @@
|
|||||||
{{ 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>
|
||||||
|
|
||||||
|
<!-- 签到倒计时:当前签到码剩余有效期,归零须重新扫码(需求补充 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,
|
||||||
|
getCheckinAuthUrl,
|
||||||
|
unwrap,
|
||||||
|
wecomCheckinPage,
|
||||||
|
wecomCheckinSession,
|
||||||
|
type TrainingSignRecord,
|
||||||
|
type WecomCheckinPageData,
|
||||||
|
type WecomCheckinSessionData,
|
||||||
|
} 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' | 'authing' | '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 })
|
||||||
|
|
||||||
|
const routeToken = computed(() => String(route.params.token || ''))
|
||||||
|
// 企微内置浏览器 UA 含 wxwork;非企微环境无法静默授权,引导改用企微扫码。
|
||||||
|
const isWecomUA = computed(() =>
|
||||||
|
typeof navigator !== 'undefined' && /wxwork/i.test(navigator.userAgent || ''),
|
||||||
|
)
|
||||||
|
|
||||||
|
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 '签到失败'
|
case 'authing':
|
||||||
|
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 || '签到码无效或已过期,请联系讲师刷新签到码'
|
case 'authing':
|
||||||
|
return '正在验证身份并打开签到页,请稍候'
|
||||||
|
case 'ready':
|
||||||
|
return page.value?.already_signed
|
||||||
|
? '本课程您已完成签到,无需重复操作'
|
||||||
|
: '请核对课程与签到人信息,点击下方按钮完成签到'
|
||||||
|
case 'submitting':
|
||||||
|
return '正在获取定位并提交签到,请保持页面打开'
|
||||||
|
case 'success':
|
||||||
|
return `签到时间:${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 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
|
||||||
|
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.in_roster) return '您不在该课程的「参加人员」名单中,请联系讲师或人事确认'
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
const signButtonText = computed(() => {
|
||||||
|
if (page.value?.already_signed) return '已签到'
|
||||||
|
if (state.value === 'submitting') return '签到中…'
|
||||||
|
return '点击签到'
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- 链路编排 ----
|
||||||
|
|
||||||
|
// 企微 OAuth 静默授权跳转:snsapi_base,学员无感;回跳落地页带 code+state。
|
||||||
|
const startOAuth = async () => {
|
||||||
|
state.value = 'authing'
|
||||||
|
try {
|
||||||
|
const res = unwrap<{ authorize_url: string }>(
|
||||||
|
await getCheckinAuthUrl(routeToken.value, `${window.location.origin}/platform/training/checkin/${routeToken.value}`),
|
||||||
|
)
|
||||||
|
if (!res?.authorize_url) throw new Error('empty authorize_url')
|
||||||
|
window.location.replace(res.authorize_url)
|
||||||
|
} catch (e: any) {
|
||||||
|
state.value = 'blocked'
|
||||||
|
errorMsg.value = e?.response?.data?.message || '免登跳转失败,请重新扫码'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuth 回跳:code 换平台会话(token/refresh_token/user/tenant/memberships,
|
||||||
|
// 与 /auth/login 同构)→ 复用登录持久化路径完成"签到即自动登录"。
|
||||||
|
const persistLogin = (data: WecomCheckinSessionData) => {
|
||||||
|
const activeTenant = data.active_tenant || null
|
||||||
|
const homeTenantIdRaw = (data.user as any)?.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 as any)?.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 exchangeSession = async (code: string, stateToken: string) => {
|
||||||
|
state.value = 'authing'
|
||||||
|
try {
|
||||||
|
const data = unwrap<WecomCheckinSessionData>(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 || '免登失败,请重新扫码'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const applyPage = (data: WecomCheckinPageData) => {
|
||||||
|
page.value = data
|
||||||
|
state.value = 'ready'
|
||||||
|
startCountdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 已登录(PC 讲师自测 / 企微内已有会话):直接取落地页数据;token 失效时在
|
||||||
|
// 企微环境回退免登链路。
|
||||||
|
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) {
|
||||||
|
if (isWecomUA.value) {
|
||||||
|
await startOAuth()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.value = 'blocked'
|
||||||
|
errorMsg.value = e?.response?.data?.message || '签到码无效或已过期,请重新扫码'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 取定位:最多等 6 秒,失败不阻塞签到(是否强制定位由后端规则决定)
|
// 取定位:最多等 6 秒,失败不阻塞签到(是否强制定位由后端规则决定)
|
||||||
const locate = () =>
|
const locate = () =>
|
||||||
new Promise<void>((resolve) => {
|
new Promise<void>((resolve) => {
|
||||||
@@ -77,29 +308,41 @@ 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 () => {
|
// 点击签到(2026-11 需求:不再进页自动签):工号 + 随机时间戳随请求提交,
|
||||||
state.value = 'pending'
|
// 后端做当天性/名单硬校验与防重放。
|
||||||
const token = String(route.params.token || '')
|
const sign = async () => {
|
||||||
if (!token) {
|
if (!page.value || signDisabled.value) return
|
||||||
state.value = 'error'
|
state.value = 'submitting'
|
||||||
errorMsg.value = '签到链接不完整'
|
errorMsg.value = ''
|
||||||
return
|
|
||||||
}
|
|
||||||
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')
|
const res = unwrap<TrainingSignRecord>(
|
||||||
record.value = (unwrap(res) as TrainingSignRecord | undefined) || null
|
await checkin(routeToken.value, geo.value.lat, geo.value.lng, 'wecom_scan', '', {
|
||||||
|
employee_no: page.value.member?.employee_no || '',
|
||||||
|
nonce,
|
||||||
|
client_ts: Date.now(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
record.value = res || null
|
||||||
state.value = 'success'
|
state.value = 'success'
|
||||||
|
stopCountdown()
|
||||||
|
// 签到成功 → 已自动登录,稍作停留后进入该课程详情页(需求补充 3)。
|
||||||
|
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 +350,32 @@ 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 回跳:优先消费一次性 code 完成免登。
|
||||||
|
exchangeSession(oauthCode, oauthState)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!routeToken.value) {
|
||||||
|
state.value = 'blocked'
|
||||||
|
errorMsg.value = '签到链接不完整'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (authStore.isLoggedIn) {
|
||||||
|
loadPage()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (isWecomUA.value) {
|
||||||
|
startOAuth()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.value = 'blocked'
|
||||||
|
errorMsg.value = '请使用企业微信「扫一扫」扫描培训签到码完成签到'
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(stopCountdown)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="less" scoped>
|
<style lang="less" scoped>
|
||||||
@@ -173,6 +441,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 +458,46 @@ 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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; }
|
||||||
|
|||||||
@@ -13,6 +13,10 @@
|
|||||||
</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>
|
||||||
|
<!-- 培训签到:跳「培训签到」页并自动定位本课程场次(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>
|
||||||
@@ -57,14 +61,6 @@
|
|||||||
active
|
active
|
||||||
fill-height
|
fill-height
|
||||||
/>
|
/>
|
||||||
<DocumentPreview
|
|
||||||
v-else-if="current && isDoc(current)"
|
|
||||||
:knowledge-id="current.knowledge_id"
|
|
||||||
:file-type="previewKind(current)"
|
|
||||||
:file-name="current.name"
|
|
||||||
active
|
|
||||||
fill-height
|
|
||||||
/>
|
|
||||||
<t-empty
|
<t-empty
|
||||||
v-else-if="current"
|
v-else-if="current"
|
||||||
class="preview-empty"
|
class="preview-empty"
|
||||||
@@ -209,7 +205,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 +220,27 @@ 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 (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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- 学习进度心跳 ----
|
// ---- 学习进度心跳 ----
|
||||||
@@ -358,6 +352,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 {
|
||||||
@@ -414,6 +414,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);
|
||||||
|
|||||||
@@ -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,6 +30,9 @@
|
|||||||
<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>
|
||||||
|
|
||||||
@@ -98,16 +101,61 @@
|
|||||||
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
||||||
/>
|
/>
|
||||||
</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 } 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 {
|
import {
|
||||||
|
downloadCourseLibraryMaterial,
|
||||||
getMyProfile,
|
getMyProfile,
|
||||||
listCourses,
|
listCourses,
|
||||||
listCourseLibrary,
|
listCourseLibrary,
|
||||||
|
listMyEnrolledCourseIds,
|
||||||
listMyExamRecords,
|
listMyExamRecords,
|
||||||
listMyLearningTasks,
|
listMyLearningTasks,
|
||||||
listSessions,
|
listSessions,
|
||||||
@@ -125,9 +173,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 +192,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 +245,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):「我的考试」页签数据源
|
||||||
@@ -164,13 +264,24 @@ const keyword = ref('')
|
|||||||
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
||||||
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
||||||
|
|
||||||
// 「和信课程」(000154):课程管理中已发布、且部门范围覆盖查看人的课程
|
// 「和信课程」(000160):已发布 + 适合人员覆盖查看人 —— 「全部」全员可见;
|
||||||
// (所属部门为空 = 全员课程;有部门则需与我的部门一致)
|
// 000159 多部门口径:值按「、」拆分(逗号/分号兼容归一)后与查看人部门名做
|
||||||
|
// 成员匹配;未设置适合人员的存量课程沿用原部门范围口径(所属部门为空 = 全员,
|
||||||
|
// 否则须与我的部门一致)。后端 scope=catalog 已按同口径过滤,此处保留客户端兜底。
|
||||||
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
||||||
|
const myDeptName = computed(() => (myProfile.value?.dept_name || '').trim())
|
||||||
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
||||||
libraryItems.value.filter(
|
libraryItems.value.filter((c) => {
|
||||||
(c) => c.publish_status === 'published' && (!c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value),
|
if (c.publish_status !== 'published') return false
|
||||||
),
|
const suitableNames = (c.suitable_members || '')
|
||||||
|
.split(/[、,,;;]/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
if (suitableNames.length) {
|
||||||
|
return suitableNames.includes('全部') || (!!myDeptName.value && suitableNames.includes(myDeptName.value))
|
||||||
|
}
|
||||||
|
return !c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const statsText = computed(() => {
|
const statsText = computed(() => {
|
||||||
@@ -206,13 +317,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 +357,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 +501,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'
|
||||||
// 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记
|
// 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记
|
||||||
@@ -441,17 +564,20 @@ const loadAll = async () => {
|
|||||||
// 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 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),
|
// (全部/本部门;未设置沿用部门范围口径),不按维护角色收窄,全体员工同源
|
||||||
|
listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => 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 +586,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 +683,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 +720,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;
|
||||||
|
|||||||
@@ -71,7 +71,7 @@
|
|||||||
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>
|
||||||
@@ -98,6 +98,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>
|
||||||
@@ -195,16 +203,17 @@
|
|||||||
</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 +224,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="随课程带出" />
|
||||||
@@ -863,12 +889,12 @@ 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 || ''
|
||||||
@@ -1159,19 +1185,40 @@ const onSave = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
|
}
|
||||||
|
if (!row.teach_time) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课时间`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!row.location) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课地点`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row.post_scope) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」发布前需先在「调整」中设置参加人员`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -1263,12 +1310,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 +1385,55 @@ 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 || '',
|
||||||
|
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 +1447,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 +1461,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 +1485,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,9 +78,14 @@
|
|||||||
<span v-else>-</span>
|
<span v-else>-</span>
|
||||||
</template>
|
</template>
|
||||||
<template #material="{ row }">
|
<template #material="{ row }">
|
||||||
<span v-if="row.material_name" class="clamp-2" :title="row.material_name">{{ row.material_name }}</span>
|
<!-- 课件只展示有/无:有=已上传文件或已挂接知识库课件,点击直达课件管理抽屉 -->
|
||||||
<span v-else>-</span>
|
<t-tag v-if="hasMaterial(row)" theme="success" variant="light" size="small" class="cell-link" @click="openMaterialDrawer(row)">有</t-tag>
|
||||||
<t-tag v-if="row.file_name" theme="success" variant="light" size="small" class="material-file-tag">附件</t-tag>
|
<t-tag v-else theme="default" variant="light" size="small">无</t-tag>
|
||||||
|
</template>
|
||||||
|
<template #question="{ row }">
|
||||||
|
<!-- 试题只展示有/无:有=课程已关联题库,点击直达试题管理抽屉 -->
|
||||||
|
<t-tag v-if="(row.question_bank_count || 0) > 0" theme="success" variant="light" size="small" class="cell-link" @click="openQuestions(row)">有</t-tag>
|
||||||
|
<t-tag v-else theme="default" variant="light" size="small">无</t-tag>
|
||||||
</template>
|
</template>
|
||||||
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
|
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
|
||||||
<!-- 创建人(联查 users):记录课程由谁录入 -->
|
<!-- 创建人(联查 users):记录课程由谁录入 -->
|
||||||
@@ -99,6 +104,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<template #op="{ row }">
|
<template #op="{ row }">
|
||||||
<t-button v-if="canEditCourse(row)" variant="text" theme="primary" size="small" @click="openForm(row)">编辑</t-button>
|
<t-button v-if="canEditCourse(row)" variant="text" theme="primary" size="small" @click="openForm(row)">编辑</t-button>
|
||||||
|
<t-button variant="text" size="small" @click="openMaterialDrawer(row)">课件</t-button>
|
||||||
<t-button variant="text" size="small" @click="openQuestions(row)">试题</t-button>
|
<t-button variant="text" size="small" @click="openQuestions(row)">试题</t-button>
|
||||||
<t-popconfirm
|
<t-popconfirm
|
||||||
v-if="canVerifyCourse(row)"
|
v-if="canVerifyCourse(row)"
|
||||||
@@ -127,7 +133,6 @@
|
|||||||
>
|
>
|
||||||
<t-button variant="text" theme="danger" size="small">删除</t-button>
|
<t-button variant="text" theme="danger" size="small">删除</t-button>
|
||||||
</t-popconfirm>
|
</t-popconfirm>
|
||||||
<t-button v-if="row.file_name" variant="text" size="small" @click="onDownloadMaterial(row)">下载课件</t-button>
|
|
||||||
</template>
|
</template>
|
||||||
</t-table>
|
</t-table>
|
||||||
</div>
|
</div>
|
||||||
@@ -142,8 +147,12 @@
|
|||||||
<t-input v-model="form.name" placeholder="请输入课程名称" />
|
<t-input v-model="form.name" placeholder="请输入课程名称" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="所属部门">
|
<t-form-item label="所属部门">
|
||||||
<!-- 对应需求表「主办单位」:从组织架构部门选择(批量导入按部门名匹配) -->
|
<!-- 对应需求表「主办单位」:锁定为创建人(当前登录人)所属部门,不可修改
|
||||||
<t-select v-model="form.owner_dept_id" clearable filterable placeholder="从组织架构选择所属部门(选填)" style="width: 100%">
|
(000160,服务端同口径强制;无部门档案时可手动选择) -->
|
||||||
|
<t-select
|
||||||
|
v-model="form.owner_dept_id" :disabled="Boolean(myDeptId)" :clearable="!myDeptId"
|
||||||
|
filterable :placeholder="myDeptId ? '创建人所属部门(不可修改)' : '从组织架构选择所属部门(选填)'" style="width: 100%"
|
||||||
|
>
|
||||||
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
|
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
|
||||||
</t-select>
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
@@ -151,8 +160,14 @@
|
|||||||
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
|
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="适合人员">
|
<t-form-item label="适合人员">
|
||||||
<!-- 对应需求表「参加人员」:自由文本,如:财会人员 -->
|
<!-- 000159 部门多选口径:归属部门(可多选)或「全部」(互斥);发布后
|
||||||
<t-input v-model="form.suitable_members" placeholder="适合参加的人员(选填),如:财会人员" />
|
培训中心按此展示给对应人员,存量自由文本值回显为选项 -->
|
||||||
|
<t-select
|
||||||
|
v-model="suitableList" clearable filterable multiple
|
||||||
|
placeholder="选择部门(可多选),或选「全部」" style="width: 100%"
|
||||||
|
>
|
||||||
|
<t-option v-for="opt in suitableOptions" :key="opt" :value="opt" :label="opt" />
|
||||||
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="分类">
|
<t-form-item label="分类">
|
||||||
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
|
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
|
||||||
@@ -181,50 +196,8 @@
|
|||||||
<t-form-item label="时长(学时)">
|
<t-form-item label="时长(学时)">
|
||||||
<t-input-number v-model="form.hours" :min="0" :step="0.5" style="width: 100%" />
|
<t-input-number v-model="form.hours" :min="0" :step="0.5" style="width: 100%" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="课件">
|
|
||||||
<div class="material-field">
|
|
||||||
<t-input v-model="form.material_name" placeholder="课件名称登记,多个用、分隔(选填)" />
|
|
||||||
<div class="material-upload-row">
|
|
||||||
<input ref="materialInputRef" type="file" class="material-upload-input" @change="onMaterialFileChange" />
|
|
||||||
<t-button variant="outline" size="small" @click="materialInputRef?.click()">上传课件文件</t-button>
|
|
||||||
<t-button variant="outline" size="small" :loading="kbDocsLoading" @click="toggleKbDocSelect">从知识库选择</t-button>
|
|
||||||
<template v-if="pendingMaterialFile">
|
|
||||||
<span class="material-file-name">{{ pendingMaterialFile.name }}</span>
|
|
||||||
<t-button variant="text" size="small" @click="clearPendingMaterialFile">移除</t-button>
|
|
||||||
</template>
|
|
||||||
<template v-else-if="pendingKbDoc">
|
|
||||||
<span class="material-file-name">{{ pendingKbDoc.name }}</span>
|
|
||||||
<t-button variant="text" size="small" @click="clearPendingKbDoc">移除</t-button>
|
|
||||||
</template>
|
|
||||||
<template v-else-if="form.file_name && !form.clear_file">
|
|
||||||
<span class="material-file-name">{{ form.file_name }}</span>
|
|
||||||
<t-button variant="text" size="small" @click="form.clear_file = true">移除</t-button>
|
|
||||||
</template>
|
|
||||||
<span v-else class="material-placeholder">未选择课件(可选;上传文档自动同步知识库,也可从知识库选择已有课件)</span>
|
|
||||||
</div>
|
|
||||||
<!-- 知识库文档下拉:点击「从知识库选择」展开(数据源:企业培训(课件)) -->
|
|
||||||
<div v-if="kbSelectVisible" class="material-upload-row">
|
|
||||||
<t-select
|
|
||||||
v-model="pendingKbDocId"
|
|
||||||
filterable
|
|
||||||
clearable
|
|
||||||
:loading="kbDocsLoading"
|
|
||||||
placeholder="选择「企业培训(课件)」知识库中的课件文档"
|
|
||||||
style="flex: 1; min-width: 0"
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<t-option v-for="d in kbDocs" :key="d.id" :value="d.id" :label="d.file_name" />
|
|
||||||
</t-select>
|
|
||||||
<t-button theme="primary" size="small" :disabled="!pendingKbDocId" @click="confirmKbDoc">确定</t-button>
|
|
||||||
<t-button variant="text" size="small" @click="kbSelectVisible = false">收起</t-button>
|
|
||||||
</div>
|
|
||||||
<div v-if="kbSelectVisible" class="form-hint">
|
|
||||||
数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;保存后与上传课件同口径(下载/月培训计划带出/AI 出题共用)。
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</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" @click="formVisible = false">取消</t-button>
|
||||||
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
|
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
|
||||||
@@ -248,6 +221,60 @@
|
|||||||
</template>
|
</template>
|
||||||
</t-dialog>
|
</t-dialog>
|
||||||
|
|
||||||
|
<!-- 课件管理抽屉:上传/知识库选择/预览/下载/移除(交互与试题维护抽屉同风格) -->
|
||||||
|
<t-drawer
|
||||||
|
v-model:visible="materialVisible"
|
||||||
|
:header="`课件管理 · ${materialCourse?.name || ''}${materialCourse?.code ? `(${materialCourse.code})` : ''}`"
|
||||||
|
size="72%"
|
||||||
|
placement="right"
|
||||||
|
attach="body"
|
||||||
|
:z-index="2600"
|
||||||
|
:footer="false"
|
||||||
|
>
|
||||||
|
<div class="bank-toolbar">
|
||||||
|
<t-radio-group :value="materialSourceMode" variant="default-filled" size="small" @change="onMaterialModeChange">
|
||||||
|
<t-radio-button value="upload">上传课件</t-radio-button>
|
||||||
|
<t-radio-button value="kb">从知识库选择</t-radio-button>
|
||||||
|
</t-radio-group>
|
||||||
|
<template v-if="materialSourceMode === 'upload'">
|
||||||
|
<input ref="materialFileInputRef" type="file" class="bank-upload-input" @change="onMaterialPicked" />
|
||||||
|
<t-button variant="outline" size="small" @click="materialFileInputRef?.click()">选择文件</t-button>
|
||||||
|
<span v-if="materialFile" class="bank-file-name">{{ materialFile.name }}</span>
|
||||||
|
<span v-else class="bank-file-placeholder">未选择文件</span>
|
||||||
|
<t-button theme="primary" size="small" :loading="materialUploading" :disabled="!materialFile" @click="onUploadMaterial">上传并关联课件</t-button>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<t-select
|
||||||
|
v-model="materialKbDocId"
|
||||||
|
filterable
|
||||||
|
clearable
|
||||||
|
:loading="kbDocsLoading"
|
||||||
|
placeholder="选择「企业培训(课件)」知识库中的课件文档"
|
||||||
|
style="width: 260px"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
<t-option v-for="d in kbDocs" :key="d.id" :value="d.id" :label="d.file_name" />
|
||||||
|
</t-select>
|
||||||
|
<t-button theme="primary" size="small" :loading="materialUploading" :disabled="!materialKbDocId" @click="onAttachMaterialKb">确定挂接</t-button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div class="form-hint">
|
||||||
|
数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;课件变更后课程回「待核验」,重新核验后方可发布;文档类课件上传后自动同步知识库(月培训计划带出/AI 出题/对话问答共用);发布课程前必须已上传课件。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<t-table v-if="materialCourse" :data="materialRows" :columns="materialColumns" row-key="key" size="small">
|
||||||
|
<template #size="{ row }">{{ row.size ? fmtSize(row.size) : '-' }}</template>
|
||||||
|
<template #op>
|
||||||
|
<t-button variant="text" theme="primary" size="small" @click="onPreviewMaterial">预览</t-button>
|
||||||
|
<t-button variant="text" theme="primary" size="small" @click="onDownloadMaterial(materialCourse)">下载</t-button>
|
||||||
|
<t-popconfirm content="移除后课程回「待核验」,需重新上传课件方可发布,确定移除?" theme="danger" @confirm="onRemoveMaterial">
|
||||||
|
<t-button variant="text" theme="danger" size="small">移除</t-button>
|
||||||
|
</t-popconfirm>
|
||||||
|
</template>
|
||||||
|
</t-table>
|
||||||
|
<t-empty v-if="materialCourse && !hasMaterial(materialCourse)" description="暂无课件,可在上方上传文件或从知识库选择;发布课程前必须已上传课件" />
|
||||||
|
</t-drawer>
|
||||||
|
|
||||||
<!-- 试题管理抽屉:题库与试题随课程条目增删改查(上传 Excel/知识库导入/AI 出题) -->
|
<!-- 试题管理抽屉:题库与试题随课程条目增删改查(上传 Excel/知识库导入/AI 出题) -->
|
||||||
<t-drawer
|
<t-drawer
|
||||||
v-model:visible="questionsVisible"
|
v-model:visible="questionsVisible"
|
||||||
@@ -468,7 +495,7 @@
|
|||||||
</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 { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
import { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
||||||
@@ -496,6 +523,7 @@ import {
|
|||||||
listQuestions,
|
listQuestions,
|
||||||
offlineCourseLibraryItem,
|
offlineCourseLibraryItem,
|
||||||
publishCourseLibraryItem,
|
publishCourseLibraryItem,
|
||||||
|
removeCourseLibraryMaterial,
|
||||||
saveCourseLibraryItem,
|
saveCourseLibraryItem,
|
||||||
saveQuestion,
|
saveQuestion,
|
||||||
uploadCourseLibraryMaterial,
|
uploadCourseLibraryMaterial,
|
||||||
@@ -525,6 +553,34 @@ const configCategories = ref<string[]>([])
|
|||||||
const myDeptId = ref('')
|
const myDeptId = ref('')
|
||||||
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
|
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
|
||||||
const myUserId = ref('')
|
const myUserId = ref('')
|
||||||
|
// 本人部门名(000160):「适合人员」默认值 = 创建人所属部门名;经 me 的
|
||||||
|
// dept_name 联查字段直取,回退本地部门名册映射。
|
||||||
|
const myDeptName = computed(() => {
|
||||||
|
const fromMe = (meDeptName.value || '').trim()
|
||||||
|
if (fromMe) return fromMe
|
||||||
|
const hit = depts.value.find((d) => d.id === myDeptId.value)
|
||||||
|
return hit?.name || ''
|
||||||
|
})
|
||||||
|
// /training/members/me 联查返回的部门名(handler 000160 起填充)
|
||||||
|
const meDeptName = ref('')
|
||||||
|
// 「适合人员」下拉选项(000160/000159 多选口径):全部 + 各部门名;存量自由文本值保留可选
|
||||||
|
const suitableOptions = computed(() => {
|
||||||
|
const opts = ['全部', ...depts.value.map((d) => d.name)]
|
||||||
|
for (const v of splitSuitable(form.value.suitable_members)) {
|
||||||
|
if (!opts.includes(v)) opts.push(v)
|
||||||
|
}
|
||||||
|
return opts
|
||||||
|
})
|
||||||
|
// 适合人员多选值(000159):form.suitable_members 存「、」join 后的落库串,
|
||||||
|
// 选项交互走本数组;「全部」与具体部门互斥(勾全部清部门,勾部门移除全部)。
|
||||||
|
const suitableList = ref<string[]>([])
|
||||||
|
const splitSuitable = (v: string) =>
|
||||||
|
(v || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
|
||||||
|
watch(suitableList, (list, prev) => {
|
||||||
|
if (list.includes('全部') && list.length > 1) {
|
||||||
|
suitableList.value = (prev || []).includes('全部') ? list.filter((v) => v !== '全部') : ['全部']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 核验/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
|
// 核验/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
|
||||||
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
|
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
|
||||||
@@ -586,7 +642,9 @@ const columns = [
|
|||||||
{ colKey: 'mode', title: '线上/线下', width: 92 },
|
{ colKey: 'mode', title: '线上/线下', width: 92 },
|
||||||
{ colKey: 'lecturer', title: '讲师', width: 110 },
|
{ colKey: 'lecturer', title: '讲师', width: 110 },
|
||||||
{ colKey: 'hours', title: '时长', width: 84 },
|
{ colKey: 'hours', title: '时长', width: 84 },
|
||||||
{ colKey: 'material', title: '课件', minWidth: 150 },
|
// 课件/试题只展示有/无:有=已上传课件或已关联题库,点击直达对应维护抽屉
|
||||||
|
{ colKey: 'material', title: '课件', width: 70 },
|
||||||
|
{ colKey: 'question', title: '试题', width: 70 },
|
||||||
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
|
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
|
||||||
{ colKey: 'publish_status', title: '发布状态', width: 90 },
|
{ colKey: 'publish_status', title: '发布状态', width: 90 },
|
||||||
{ colKey: 'created_at', title: '创建时间', width: 140 },
|
{ colKey: 'created_at', title: '创建时间', width: 140 },
|
||||||
@@ -618,6 +676,7 @@ const loadAll = async () => {
|
|||||||
const meBody = me && unwrap(me)
|
const meBody = me && unwrap(me)
|
||||||
myDeptId.value = meBody?.dept_id || ''
|
myDeptId.value = meBody?.dept_id || ''
|
||||||
myUserId.value = meBody?.user_id || ''
|
myUserId.value = meBody?.user_id || ''
|
||||||
|
meDeptName.value = meBody?.dept_name || ''
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
loading.value = false
|
||||||
}
|
}
|
||||||
@@ -626,7 +685,9 @@ const loadAll = async () => {
|
|||||||
// ---- 新增/编辑 ----
|
// ---- 新增/编辑 ----
|
||||||
|
|
||||||
const formVisible = ref(false)
|
const formVisible = ref(false)
|
||||||
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析
|
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析。
|
||||||
|
// material_name 为隐藏保留字段:课件维护移至「课件」抽屉后,编辑保存仍原值回传,
|
||||||
|
// 防止全量更新把名称登记误清(000162)。
|
||||||
const form = ref({
|
const form = ref({
|
||||||
id: '',
|
id: '',
|
||||||
code: '',
|
code: '',
|
||||||
@@ -636,43 +697,19 @@ const form = ref({
|
|||||||
suitable_members: '',
|
suitable_members: '',
|
||||||
category: '',
|
category: '',
|
||||||
type: 'required' as 'required' | 'elective',
|
type: 'required' as 'required' | 'elective',
|
||||||
mode: 'offline' as 'offline' | 'online',
|
// 新增默认「线上」(000162):线上课为常规形态;编辑随原值
|
||||||
|
mode: 'online' as 'offline' | 'online',
|
||||||
lecturer: '',
|
lecturer: '',
|
||||||
hours: 0,
|
hours: 0,
|
||||||
material_name: '',
|
material_name: '',
|
||||||
file_name: '',
|
|
||||||
clear_file: false,
|
|
||||||
})
|
})
|
||||||
// 待上传课件文件(保存成功后随行上传)
|
|
||||||
const materialInputRef = ref<HTMLInputElement | null>(null)
|
|
||||||
const pendingMaterialFile = ref<File | null>(null)
|
|
||||||
|
|
||||||
const onMaterialFileChange = (e: Event) => {
|
// ---- 「企业培训(课件)」知识库文档(课件抽屉「从知识库选择」数据源) ----
|
||||||
const input = e.target as HTMLInputElement
|
|
||||||
pendingMaterialFile.value = input.files?.[0] || null
|
|
||||||
input.value = ''
|
|
||||||
// 上传文件与知识库课件二选一:选择文件即清掉已选知识库文档
|
|
||||||
clearPendingKbDoc()
|
|
||||||
}
|
|
||||||
const clearPendingMaterialFile = () => {
|
|
||||||
pendingMaterialFile.value = null
|
|
||||||
if (materialInputRef.value) materialInputRef.value.value = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- 从知识库选择课件(企业培训(课件)) ----
|
|
||||||
const kbSelectVisible = ref(false)
|
|
||||||
const pendingKbDocId = ref('')
|
|
||||||
const pendingKbDoc = ref<{ id: string; name: string } | null>(null)
|
|
||||||
const kbDocs = ref<{ id: string; file_name: string }[]>([])
|
const kbDocs = ref<{ id: string; file_name: string }[]>([])
|
||||||
const kbDocsLoading = ref(false)
|
const kbDocsLoading = ref(false)
|
||||||
const coursewareKbRef = ref<{ id: string; name: string } | null>(null)
|
const coursewareKbRef = ref<{ id: string; name: string } | null>(null)
|
||||||
let kbDocsLoaded = false
|
let kbDocsLoaded = false
|
||||||
|
|
||||||
const toggleKbDocSelect = async () => {
|
|
||||||
kbSelectVisible.value = !kbSelectVisible.value
|
|
||||||
if (kbSelectVisible.value) await loadCoursewareKbDocs()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 拉取「企业培训(课件)」知识库文档列表(惰性加载一次)
|
// 拉取「企业培训(课件)」知识库文档列表(惰性加载一次)
|
||||||
const loadCoursewareKbDocs = async () => {
|
const loadCoursewareKbDocs = async () => {
|
||||||
if (kbDocsLoaded) return
|
if (kbDocsLoaded) return
|
||||||
@@ -700,24 +737,6 @@ const loadCoursewareKbDocs = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const confirmKbDoc = () => {
|
|
||||||
const doc = kbDocs.value.find((d) => d.id === pendingKbDocId.value)
|
|
||||||
if (!doc) {
|
|
||||||
MessagePlugin.warning('请先选择知识库课件文档')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pendingKbDoc.value = { id: doc.id, name: doc.file_name }
|
|
||||||
// 与上传文件互斥:选定知识库文档即清掉待上传文件与已有文件移除标记
|
|
||||||
clearPendingMaterialFile()
|
|
||||||
form.value.clear_file = false
|
|
||||||
kbSelectVisible.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
const clearPendingKbDoc = () => {
|
|
||||||
pendingKbDoc.value = null
|
|
||||||
pendingKbDocId.value = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
// 讲师下拉选项:全体员工(id=平台用户 id,与课程/需求讲师字段口径一致);
|
// 讲师下拉选项:全体员工(id=平台用户 id,与课程/需求讲师字段口径一致);
|
||||||
// 编辑外部讲师(非 id 值)时追加临时选项避免回显裸文本丢失
|
// 编辑外部讲师(非 id 值)时追加临时选项避免回显裸文本丢失
|
||||||
const lecturerSelectOptions = computed(() => {
|
const lecturerSelectOptions = computed(() => {
|
||||||
@@ -732,26 +751,25 @@ const lecturerSelectOptions = computed(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const openForm = (row?: TrainingLibraryCourse) => {
|
const openForm = (row?: TrainingLibraryCourse) => {
|
||||||
clearPendingMaterialFile()
|
|
||||||
clearPendingKbDoc()
|
|
||||||
kbSelectVisible.value = false
|
|
||||||
form.value = {
|
form.value = {
|
||||||
id: row?.id || '',
|
id: row?.id || '',
|
||||||
code: row?.code || '',
|
code: row?.code || '',
|
||||||
name: row?.name || '',
|
name: row?.name || '',
|
||||||
// 新增默认当前登录用户所在部门;编辑保持原部门
|
// 新增默认当前登录用户所在部门(锁定不可改);编辑保持原部门
|
||||||
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
||||||
description: row?.description || '',
|
description: row?.description || '',
|
||||||
suitable_members: row?.suitable_members || '',
|
// 适合人员(000160):新增默认创建人所属部门名,可改「全部」或其他部门
|
||||||
|
suitable_members: row?.suitable_members || (row ? '' : myDeptName.value),
|
||||||
category: row?.category || '',
|
category: row?.category || '',
|
||||||
type: row?.type === 'elective' ? 'elective' : 'required',
|
type: row?.type === 'elective' ? 'elective' : 'required',
|
||||||
mode: row?.mode === 'online' ? 'online' : 'offline',
|
// 新增默认「线上」(000162);编辑随原值
|
||||||
|
mode: row ? (row.mode === 'online' ? 'online' : 'offline') : 'online',
|
||||||
lecturer: row?.lecturer_id || row?.lecturer_external || '',
|
lecturer: row?.lecturer_id || row?.lecturer_external || '',
|
||||||
hours: row?.hours || 0,
|
hours: row?.hours || 0,
|
||||||
material_name: row?.material_name || '',
|
material_name: row?.material_name || '',
|
||||||
file_name: row?.file_name || '',
|
|
||||||
clear_file: false,
|
|
||||||
}
|
}
|
||||||
|
// 适合人员多选回显(000159):落库串「、」join → 数组;新增默认本部门
|
||||||
|
suitableList.value = splitSuitable(form.value.suitable_members)
|
||||||
formVisible.value = true
|
formVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -771,6 +789,8 @@ const onSave = async () => {
|
|||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const lecturer = resolveLecturer(form.value.lecturer.trim())
|
const lecturer = resolveLecturer(form.value.lecturer.trim())
|
||||||
|
// 适合人员多选 → 「、」join 落库(000159);「全部」与部门互斥由 watch 保证
|
||||||
|
form.value.suitable_members = suitableList.value.join('、')
|
||||||
const res = await saveCourseLibraryItem({
|
const res = await saveCourseLibraryItem({
|
||||||
id: form.value.id || undefined,
|
id: form.value.id || undefined,
|
||||||
name: form.value.name.trim(),
|
name: form.value.name.trim(),
|
||||||
@@ -783,21 +803,10 @@ const onSave = async () => {
|
|||||||
lecturer_id: lecturer.lecturer_id || undefined,
|
lecturer_id: lecturer.lecturer_id || undefined,
|
||||||
lecturer_external: lecturer.lecturer_external || undefined,
|
lecturer_external: lecturer.lecturer_external || undefined,
|
||||||
hours: form.value.hours,
|
hours: form.value.hours,
|
||||||
|
// 隐藏保留字段:课件维护已移至「课件」抽屉,编辑保存原值回传防误清(000162)
|
||||||
material_name: form.value.material_name.trim(),
|
material_name: form.value.material_name.trim(),
|
||||||
clear_file: form.value.clear_file || undefined,
|
|
||||||
})
|
})
|
||||||
const saved = unwrap(res)
|
const saved = unwrap(res)
|
||||||
// 待上传课件文件:条目已落库后随行上传(名称登记为空时后端以文件名兜底;
|
|
||||||
// 文档类自动同步知识库「企业培训(课件)」,支持 AI 对话与出题)
|
|
||||||
if (pendingMaterialFile.value && saved?.id) {
|
|
||||||
const fd = new FormData()
|
|
||||||
fd.append('file', pendingMaterialFile.value)
|
|
||||||
await uploadCourseLibraryMaterial(saved.id, fd)
|
|
||||||
}
|
|
||||||
// 从知识库选择的课件:保存后挂接知识库文档(与上传同步同口径)
|
|
||||||
if (pendingKbDoc.value && saved?.id) {
|
|
||||||
await attachCourseLibraryMaterialFromKb(saved.id, { knowledge_id: pendingKbDoc.value.id })
|
|
||||||
}
|
|
||||||
MessagePlugin.success(
|
MessagePlugin.success(
|
||||||
form.value.id
|
form.value.id
|
||||||
? saved?.code
|
? saved?.code
|
||||||
@@ -808,8 +817,6 @@ const onSave = async () => {
|
|||||||
: '课程已创建,可在「月培训计划」中引用',
|
: '课程已创建,可在「月培训计划」中引用',
|
||||||
)
|
)
|
||||||
formVisible.value = false
|
formVisible.value = false
|
||||||
clearPendingMaterialFile()
|
|
||||||
clearPendingKbDoc()
|
|
||||||
loadAll()
|
loadAll()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
|
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
|
||||||
@@ -902,6 +909,11 @@ const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published
|
|||||||
MessagePlugin.warning('该课程尚未核验,请先由本部门课长/经理核验确认后再发布')
|
MessagePlugin.warning('该课程尚未核验,请先由本部门课长/经理核验确认后再发布')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 发布前置校验(000162):必须有课件(名称登记不算,后端兜底同样拦截)
|
||||||
|
if (status === 'published' && !hasMaterial(row)) {
|
||||||
|
MessagePlugin.warning('该课程尚未上传课件,请先在「课件」入口上传课件文件(或从知识库选择)后再发布')
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const updated = unwrap(
|
const updated = unwrap(
|
||||||
status === 'published' ? await publishCourseLibraryItem(row.id) : await offlineCourseLibraryItem(row.id),
|
status === 'published' ? await publishCourseLibraryItem(row.id) : await offlineCourseLibraryItem(row.id),
|
||||||
@@ -920,7 +932,11 @@ const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const onDownloadMaterial = async (row: TrainingLibraryCourse) => {
|
// 课件有无口径:已上传原始文件或已挂接知识库课件文档(名称登记不算,与发布校验同口径)
|
||||||
|
const hasMaterial = (row: TrainingLibraryCourse) => Boolean(row.file_name || row.knowledge_id)
|
||||||
|
|
||||||
|
const onDownloadMaterial = async (row: TrainingLibraryCourse | null) => {
|
||||||
|
if (!row) return
|
||||||
try {
|
try {
|
||||||
// getDown 直接返回 Blob(trainingTemplates 同款消费方式)
|
// getDown 直接返回 Blob(trainingTemplates 同款消费方式)
|
||||||
const blob = await downloadCourseLibraryMaterial(row.id)
|
const blob = await downloadCourseLibraryMaterial(row.id)
|
||||||
@@ -935,6 +951,142 @@ const onDownloadMaterial = async (row: TrainingLibraryCourse) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 课件管理抽屉(000162):上传/知识库选择/预览/下载/移除,交互与试题抽屉同风格
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const materialVisible = ref(false)
|
||||||
|
const materialCourse = ref<TrainingLibraryCourse | null>(null)
|
||||||
|
const materialUploading = ref(false)
|
||||||
|
type MaterialSourceMode = 'upload' | 'kb'
|
||||||
|
const materialSourceMode = ref<MaterialSourceMode>('upload')
|
||||||
|
const materialFileInputRef = ref<HTMLInputElement | null>(null)
|
||||||
|
const materialFile = ref<File | null>(null)
|
||||||
|
const materialKbDocId = ref('')
|
||||||
|
|
||||||
|
const materialColumns = [
|
||||||
|
{ colKey: 'name', title: '课件名称', minWidth: 220 },
|
||||||
|
{ colKey: 'size', title: '大小', width: 110 },
|
||||||
|
{ colKey: 'source', title: '来源', width: 130 },
|
||||||
|
{ colKey: 'op', title: '操作', width: 190 },
|
||||||
|
]
|
||||||
|
|
||||||
|
const fmtSize = (size: number) => {
|
||||||
|
if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`
|
||||||
|
if (size >= 1024) return `${Math.round(size / 1024)} KB`
|
||||||
|
return `${size} B`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 抽屉内课件信息行:与列表「有」口径一致(文件或知识库文档任一存在)
|
||||||
|
const materialRows = computed(() => {
|
||||||
|
const c = materialCourse.value
|
||||||
|
if (!c || !hasMaterial(c)) return []
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
key: 'material',
|
||||||
|
name: c.file_name || c.material_name || '知识库课件文档',
|
||||||
|
size: c.file_size || 0,
|
||||||
|
source: c.file_name ? '本地上传文件' : '知识库文档',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
// 列表行原位替换:课件变更回「待核验」等状态随接口响应同步到列表与抽屉
|
||||||
|
const replaceLibraryRow = (updated?: TrainingLibraryCourse | null) => {
|
||||||
|
if (!updated) return
|
||||||
|
const idx = items.value.findIndex((it) => it.id === updated.id)
|
||||||
|
if (idx >= 0) items.value.splice(idx, 1, updated)
|
||||||
|
if (materialCourse.value?.id === updated.id) materialCourse.value = updated
|
||||||
|
if (questionsCourse.value?.id === updated.id) questionsCourse.value = updated
|
||||||
|
}
|
||||||
|
|
||||||
|
const openMaterialDrawer = (row: TrainingLibraryCourse) => {
|
||||||
|
materialCourse.value = row
|
||||||
|
materialVisible.value = true
|
||||||
|
materialSourceMode.value = 'upload'
|
||||||
|
materialFile.value = null
|
||||||
|
materialKbDocId.value = ''
|
||||||
|
if (materialFileInputRef.value) materialFileInputRef.value.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const onMaterialModeChange = (mode: unknown) => {
|
||||||
|
materialSourceMode.value = mode as MaterialSourceMode
|
||||||
|
if (materialSourceMode.value === 'kb') void loadCoursewareKbDocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onMaterialPicked = (e: Event) => {
|
||||||
|
const input = e.target as HTMLInputElement
|
||||||
|
materialFile.value = input.files?.[0] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
const onUploadMaterial = async () => {
|
||||||
|
const course = materialCourse.value
|
||||||
|
const file = materialFile.value
|
||||||
|
if (!course || !file) return
|
||||||
|
materialUploading.value = true
|
||||||
|
try {
|
||||||
|
const fd = new FormData()
|
||||||
|
fd.append('file', file)
|
||||||
|
// 名称登记为空时后端以文件名兜底;文档类自动同步知识库「企业培训(课件)」
|
||||||
|
const updated = unwrap<TrainingLibraryCourse>(await uploadCourseLibraryMaterial(course.id, fd))
|
||||||
|
replaceLibraryRow(updated)
|
||||||
|
materialFile.value = null
|
||||||
|
if (materialFileInputRef.value) materialFileInputRef.value.value = ''
|
||||||
|
MessagePlugin.success(`课件「${updated?.file_name || file.name}」已上传;课程回「待核验」,核验后方可发布`)
|
||||||
|
} catch (e: any) {
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '课件上传失败'))
|
||||||
|
} finally {
|
||||||
|
materialUploading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onAttachMaterialKb = async () => {
|
||||||
|
const course = materialCourse.value
|
||||||
|
const doc = kbDocs.value.find((d) => d.id === materialKbDocId.value)
|
||||||
|
if (!course || !doc) return
|
||||||
|
materialUploading.value = true
|
||||||
|
try {
|
||||||
|
const updated = unwrap<TrainingLibraryCourse>(
|
||||||
|
await attachCourseLibraryMaterialFromKb(course.id, { knowledge_id: doc.id }),
|
||||||
|
)
|
||||||
|
replaceLibraryRow(updated)
|
||||||
|
materialKbDocId.value = ''
|
||||||
|
MessagePlugin.success(`课件「${updated?.file_name || doc.file_name}」已挂接;课程回「待核验」,核验后方可发布`)
|
||||||
|
} catch (e: any) {
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '课件挂接失败'))
|
||||||
|
} finally {
|
||||||
|
materialUploading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 预览:取回 Blob 后新开页签展示(文件端点对安全类型 inline,浏览器按类型渲染;
|
||||||
|
// 不可预览类型浏览器按附件处理,回退下载)
|
||||||
|
const onPreviewMaterial = async () => {
|
||||||
|
const course = materialCourse.value
|
||||||
|
if (!course) return
|
||||||
|
try {
|
||||||
|
const blob = await downloadCourseLibraryMaterial(course.id)
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
window.open(url, '_blank')
|
||||||
|
// 延迟回收对象 URL,留足新页签加载时间
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 60_000)
|
||||||
|
} catch (e: any) {
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '课件预览失败'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onRemoveMaterial = async () => {
|
||||||
|
const course = materialCourse.value
|
||||||
|
if (!course) return
|
||||||
|
try {
|
||||||
|
const updated = unwrap<TrainingLibraryCourse>(await removeCourseLibraryMaterial(course.id))
|
||||||
|
replaceLibraryRow(updated)
|
||||||
|
MessagePlugin.success('课件已移除;课程回「待核验」,需重新上传课件后方可发布')
|
||||||
|
} catch (e: any) {
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '课件移除失败'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- 导出(当前筛选结果,列口径与模板一致) ----
|
// ---- 导出(当前筛选结果,列口径与模板一致) ----
|
||||||
|
|
||||||
const onExport = async () => {
|
const onExport = async () => {
|
||||||
@@ -1152,6 +1304,10 @@ const loadBanks = async () => {
|
|||||||
try {
|
try {
|
||||||
const res = await listLibraryCourseQuestionBanks(course.id)
|
const res = await listLibraryCourseQuestionBanks(course.id)
|
||||||
banks.value = unwrap(res) || []
|
banks.value = unwrap(res) || []
|
||||||
|
// 题库增删后同步列表「试题」有/无计数(该端点即本课程全部题库)
|
||||||
|
course.question_bank_count = banks.value.length
|
||||||
|
const idx = items.value.findIndex((it) => it.id === course.id)
|
||||||
|
if (idx >= 0) items.value[idx].question_bank_count = banks.value.length
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
MessagePlugin.error(apiErrorMessage(e, '题库加载失败'))
|
MessagePlugin.error(apiErrorMessage(e, '题库加载失败'))
|
||||||
} finally {
|
} finally {
|
||||||
@@ -1336,7 +1492,7 @@ const onGenerateQuestions = async () => {
|
|||||||
const course = questionsCourse.value
|
const course = questionsCourse.value
|
||||||
if (!course) return
|
if (!course) return
|
||||||
if (!course.knowledge_id) {
|
if (!course.knowledge_id) {
|
||||||
MessagePlugin.warning('该课程课件未同步知识库,请先在课程表单中上传课件文档后再 AI 出题')
|
MessagePlugin.warning('该课程课件未同步知识库,请先在「课件」入口上传课件文档后再 AI 出题')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
genLoading.value = true
|
genLoading.value = true
|
||||||
@@ -1539,39 +1695,9 @@ onMounted(loadAll)
|
|||||||
font-size: var(--app-text-sm);
|
font-size: var(--app-text-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 课件字段:名称登记 + 文件上传行
|
// 列表「有」标签可点击直达维护抽屉
|
||||||
.material-field {
|
.cell-link {
|
||||||
width: 100%;
|
cursor: pointer;
|
||||||
}
|
|
||||||
|
|
||||||
.material-upload-row {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 8px;
|
|
||||||
margin-top: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.material-upload-input {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.material-file-name {
|
|
||||||
max-width: 220px;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
color: var(--td-text-color-secondary);
|
|
||||||
font-size: var(--app-text-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.material-placeholder {
|
|
||||||
color: var(--td-text-color-placeholder);
|
|
||||||
font-size: var(--app-text-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.material-file-tag {
|
|
||||||
margin-left: 6px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 批量导入弹窗:模板下载 + Excel 上传一行排布(与培训计划导入同款)
|
// 批量导入弹窗:模板下载 + Excel 上传一行排布(与培训计划导入同款)
|
||||||
|
|||||||
@@ -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>
|
|
||||||
@@ -126,15 +126,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 +206,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,7 +244,7 @@
|
|||||||
</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'
|
||||||
@@ -332,13 +341,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)) {
|
||||||
@@ -552,6 +583,7 @@ const onOpenDemandForm = () => {
|
|||||||
lecturer: '',
|
lecturer: '',
|
||||||
remark: '',
|
remark: '',
|
||||||
}
|
}
|
||||||
|
demandSuitableList.value = []
|
||||||
demandFormVisible.value = true
|
demandFormVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -588,6 +620,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 +633,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 +650,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 +712,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 +792,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 +809,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 +835,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 +854,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 +864,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,12 @@
|
|||||||
有效期至 {{ fmtTime(signCode.expire_at) }}
|
有效期至 {{ fmtTime(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>
|
||||||
|
<!-- 自动轮换倒计时(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 +65,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')" />
|
||||||
@@ -150,8 +165,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 {
|
||||||
@@ -182,6 +197,7 @@ import { fmtBeijingTime } from '@/utils/datetime'
|
|||||||
|
|
||||||
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,6 +213,15 @@ 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[]>([])
|
||||||
@@ -236,6 +261,60 @@ const buildSignQr = async () => {
|
|||||||
}
|
}
|
||||||
watch(signCode, buildSignQr, { immediate: true })
|
watch(signCode, buildSignQr, { immediate: true })
|
||||||
|
|
||||||
|
// ---- 签到码自动轮换(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 || '课程'
|
||||||
@@ -464,7 +543,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 +601,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 {
|
||||||
|
|||||||
@@ -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,36 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 学习/积分/规则/通知
|
// 学习/积分/规则/通知
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -31,6 +31,21 @@ 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):仅已发布 + 适合人员覆盖调用方。
|
||||||
|
// suitable='全部' 全员可见;000159 多部门口径:值按「、」拆分(逗号/分号
|
||||||
|
// 兼容归一)后与调用方部门名做成员匹配;未设置适合人员的存量课程沿用
|
||||||
|
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。调用方
|
||||||
|
// 无部门档案时只见「全部」与未设置的课程。
|
||||||
|
if q.CatalogOnly {
|
||||||
|
tx = tx.Where("tr_course_library.publish_status = ?", "published")
|
||||||
|
tx = tx.Where(
|
||||||
|
"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 = ?)))",
|
||||||
|
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var total int64
|
var total int64
|
||||||
if err := tx.Count(&total).Error; err != nil {
|
if err := tx.Count(&total).Error; err != nil {
|
||||||
@@ -48,8 +63,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 +76,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
|
||||||
|
|||||||
@@ -119,6 +119,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,
|
||||||
@@ -527,6 +528,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 +751,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 +794,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 +825,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
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"},
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -130,9 +130,12 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 +145,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
|
||||||
}
|
}
|
||||||
@@ -172,6 +175,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 +264,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 +274,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 +394,54 @@ 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 {
|
||||||
|
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 +653,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 +711,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 +721,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 +756,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 +852,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 +866,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 +927,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 +938,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 +954,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 +968,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
|
||||||
|
|||||||
@@ -1135,6 +1135,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 != "" {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
@@ -9,6 +10,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"
|
||||||
@@ -107,6 +109,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 {
|
||||||
@@ -131,6 +138,8 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
|||||||
if item.KnowledgeID == "" {
|
if item.KnowledgeID == "" {
|
||||||
item.KnowledgeID = old.KnowledgeID
|
item.KnowledgeID = old.KnowledgeID
|
||||||
}
|
}
|
||||||
|
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
|
||||||
|
item.OwnerDeptID = old.OwnerDeptID
|
||||||
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
|
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
|
||||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||||
item.ConfirmedBy = ""
|
item.ConfirmedBy = ""
|
||||||
@@ -170,7 +179,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,6 +192,9 @@ func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, ten
|
|||||||
if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed {
|
if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed {
|
||||||
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name))
|
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name))
|
||||||
}
|
}
|
||||||
|
if status == "published" && strings.TrimSpace(item.FileKey) == "" && strings.TrimSpace(item.KnowledgeID) == "" {
|
||||||
|
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name))
|
||||||
|
}
|
||||||
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
|
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,6 +228,51 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
|
|||||||
return verified, skipped, nil
|
return verified, skipped, 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,
|
||||||
|
}
|
||||||
|
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 后逐行提交,讲师已在
|
||||||
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
||||||
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
||||||
@@ -380,6 +438,29 @@ func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tena
|
|||||||
return rc, item.FileName, nil
|
return rc, item.FileName, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveCourseLibraryMaterial 移除课程课件原始文件/知识库挂接(名称登记保留,
|
||||||
|
// 上传课件时仍会以文件名兜底名称登记):文件与知识库文档字段清空,课件内容
|
||||||
|
// 变更即回待核验(000157 同口径),移除后课程不满足发布课件前置。
|
||||||
|
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||||
|
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||||
|
if err != nil || item == nil {
|
||||||
|
return nil, werrors.NewNotFoundError("课程不存在")
|
||||||
|
}
|
||||||
|
if item.FileKey == "" && item.KnowledgeID == "" {
|
||||||
|
return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除")
|
||||||
|
}
|
||||||
|
item.FileKey, item.FileName, item.FileSize = "", "", 0
|
||||||
|
item.KnowledgeID = ""
|
||||||
|
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||||
|
item.ConfirmedBy = ""
|
||||||
|
item.ConfirmedAt = nil
|
||||||
|
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s operator=%s", tenantID, id, updaterID)
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
|
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
|
||||||
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
|
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
|
||||||
// 原始文件字段清空,名称登记为空时以文档名兜底。
|
// 原始文件字段清空,名称登记为空时以文档名兜底。
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"academy/internal/application/repository"
|
||||||
|
"academy/internal/types"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newCourseLibraryFixture 构建 sqlite + 真实仓储的 trainingService,专测课程
|
||||||
|
// 管理发布课件前置(发布必须有课件)、计划形式与课程形式解耦、列表题库计数。
|
||||||
|
// GetCourseLibraryItem/ListCourseLibrary LEFT JOIN users/org_depts 取姓名列,
|
||||||
|
// sqlite 下以最小列表兜底(仅被 JOIN 读取,不落数据)。
|
||||||
|
func newCourseLibraryFixture(t *testing.T) (*trainingService, *gorm.DB, uint64) {
|
||||||
|
t.Helper()
|
||||||
|
db, err := gorm.Open(
|
||||||
|
sqlite.Open(filepath.Join(t.TempDir(), "training_library.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
|
||||||
|
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent)},
|
||||||
|
)
|
||||||
|
require.NoError(t, err)
|
||||||
|
raw, err := db.DB()
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = raw.Close() })
|
||||||
|
require.NoError(t, db.AutoMigrate(&types.TrainingCourseLibrary{}, &types.TrainingQuestionBank{}))
|
||||||
|
for _, ddl := range []string{
|
||||||
|
"CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT DEFAULT '', display_name TEXT DEFAULT '')",
|
||||||
|
"CREATE TABLE org_depts (id TEXT PRIMARY KEY, tenant_id INTEGER DEFAULT 0, name TEXT DEFAULT '', deleted_at DATETIME NULL)",
|
||||||
|
} {
|
||||||
|
require.NoError(t, db.Exec(ddl).Error)
|
||||||
|
}
|
||||||
|
const tenantID = uint64(42)
|
||||||
|
svc := &trainingService{repo: repository.NewTrainingRepository(db), db: db}
|
||||||
|
return svc, db, tenantID
|
||||||
|
}
|
||||||
|
|
||||||
|
// seedCourseLibraryItem 直接落一条课程管理条目(绕过编号生成等依赖)。
|
||||||
|
func seedCourseLibraryItem(t *testing.T, db *gorm.DB, tenantID uint64, item *types.TrainingCourseLibrary) {
|
||||||
|
t.Helper()
|
||||||
|
if item.TenantID == 0 {
|
||||||
|
item.TenantID = tenantID
|
||||||
|
}
|
||||||
|
require.NoError(t, db.Create(item).Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发布必须有课件(000162 口径):名称登记不算,须有原始文件或知识库课件文档;
|
||||||
|
// 下线不要求课件;未核验仍先行拦截(校验顺序:核验在前课件在后)。
|
||||||
|
func TestSetCourseLibraryPublishStatusRequiresCourseware(t *testing.T) {
|
||||||
|
svc, db, tenantID := newCourseLibraryFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
nameOnly := &types.TrainingCourseLibrary{ID: "cl-name-only", Name: "仅名称登记课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, MaterialName: "安全操作规范", Mode: types.TrainingCourseModeOnline}
|
||||||
|
withFile := &types.TrainingCourseLibrary{ID: "cl-with-file", Name: "已传文件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, FileKey: "fk-1", FileName: "a.pptx", Mode: types.TrainingCourseModeOnline}
|
||||||
|
withKb := &types.TrainingCourseLibrary{ID: "cl-with-kb", Name: "知识库课件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed, KnowledgeID: "kb-1", FileName: "b.docx", Mode: types.TrainingCourseModeOnline}
|
||||||
|
pending := &types.TrainingCourseLibrary{ID: "cl-pending", Name: "待核验课程", VerifyStatus: types.CourseLibraryVerifyPending, FileKey: "fk-2", FileName: "c.pptx", Mode: types.TrainingCourseModeOnline}
|
||||||
|
for _, item := range []*types.TrainingCourseLibrary{nameOnly, withFile, withKb, pending} {
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 仅名称登记:拦截。
|
||||||
|
err := svc.SetCourseLibraryPublishStatus(ctx, tenantID, nameOnly.ID, "published")
|
||||||
|
require.Error(t, err)
|
||||||
|
require.True(t, strings.Contains(err.Error(), "课件"), "应提示缺少课件,实际: %s", err.Error())
|
||||||
|
|
||||||
|
// 已上传原始文件:放行。
|
||||||
|
require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, withFile.ID, "published"))
|
||||||
|
// 仅挂接知识库文档:放行。
|
||||||
|
require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, withKb.ID, "published"))
|
||||||
|
|
||||||
|
// 未核验(待核验)先行拦截,课件校验在其后。
|
||||||
|
err = svc.SetCourseLibraryPublishStatus(ctx, tenantID, pending.ID, "published")
|
||||||
|
require.Error(t, err)
|
||||||
|
require.True(t, strings.Contains(err.Error(), "核验"), "应提示未核验,实际: %s", err.Error())
|
||||||
|
|
||||||
|
// 下线不要求课件:名称登记课程可直接下线。
|
||||||
|
require.NoError(t, svc.SetCourseLibraryPublishStatus(ctx, tenantID, nameOnly.ID, "offline"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除课件:文件/知识库字段清空、名称登记保留、回待核验并清核验痕迹;
|
||||||
|
// 无课件条目移除直接拒绝。
|
||||||
|
func TestRemoveCourseLibraryMaterial(t *testing.T) {
|
||||||
|
svc, db, tenantID := newCourseLibraryFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
confirmedAt := timeNowPtr()
|
||||||
|
item := &types.TrainingCourseLibrary{
|
||||||
|
ID: "cl-remove", Name: "待移除课件课程", VerifyStatus: types.CourseLibraryVerifyConfirmed,
|
||||||
|
ConfirmedBy: "u-verifier", ConfirmedAt: confirmedAt,
|
||||||
|
FileKey: "fk-3", FileName: "d.pptx", FileSize: 1024, KnowledgeID: "kb-2",
|
||||||
|
MaterialName: "登记名称保留", Mode: types.TrainingCourseModeOnline,
|
||||||
|
}
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, item)
|
||||||
|
|
||||||
|
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Empty(t, updated.FileKey)
|
||||||
|
require.Empty(t, updated.FileName)
|
||||||
|
require.Zero(t, updated.FileSize)
|
||||||
|
require.Empty(t, updated.KnowledgeID)
|
||||||
|
require.Equal(t, "登记名称保留", updated.MaterialName)
|
||||||
|
require.Equal(t, types.CourseLibraryVerifyPending, updated.VerifyStatus)
|
||||||
|
require.Empty(t, updated.ConfirmedBy)
|
||||||
|
require.Nil(t, updated.ConfirmedAt)
|
||||||
|
|
||||||
|
// 落库复核(更新为全列覆盖,防只改内存对象)。
|
||||||
|
stored, err := svc.GetCourseLibraryItem(ctx, tenantID, item.ID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Empty(t, stored.FileKey)
|
||||||
|
require.Empty(t, stored.KnowledgeID)
|
||||||
|
require.Equal(t, types.CourseLibraryVerifyPending, stored.VerifyStatus)
|
||||||
|
|
||||||
|
// 已无课件再移除:拒绝。
|
||||||
|
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op")
|
||||||
|
require.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func timeNowPtr() *time.Time {
|
||||||
|
v := time.Now()
|
||||||
|
return &v
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计划「形式」与课程「线上/线下」独立(000162):绑定带出名称/类型,不覆盖
|
||||||
|
// 计划侧 mode——课程线下 + 计划线上、课程线上 + 计划线下双向保持请求值。
|
||||||
|
func TestApplyLibraryCourseBindingKeepsPlanMode(t *testing.T) {
|
||||||
|
svc, db, tenantID := newCourseLibraryFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "lib-offline", Name: "线下课程A", Type: "required", Mode: types.TrainingCourseModeOffline})
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "lib-online", Name: "线上课程B", Type: "elective", Mode: types.TrainingCourseModeOnline})
|
||||||
|
|
||||||
|
// 线下课程 + 线上计划:计划形式保持线上。
|
||||||
|
plan := &types.TrainingCourse{ID: "plan-1", LibraryCourseID: "lib-offline", Name: "占位", Mode: types.TrainingCourseModeOnline, Type: "elective"}
|
||||||
|
hit := svc.applyLibraryCourseBinding(ctx, tenantID, plan, true)
|
||||||
|
require.NotNil(t, hit)
|
||||||
|
require.Equal(t, types.TrainingCourseModeOnline, plan.Mode)
|
||||||
|
require.Equal(t, "线下课程A", plan.Name)
|
||||||
|
require.Equal(t, "required", plan.Type)
|
||||||
|
|
||||||
|
// 线上课程 + 线下计划:计划形式保持线下。
|
||||||
|
plan2 := &types.TrainingCourse{ID: "plan-2", LibraryCourseID: "lib-online", Name: "占位", Mode: types.TrainingCourseModeOffline, Type: "required"}
|
||||||
|
hit2 := svc.applyLibraryCourseBinding(ctx, tenantID, plan2, false)
|
||||||
|
require.NotNil(t, hit2)
|
||||||
|
require.Equal(t, types.TrainingCourseModeOffline, plan2.Mode)
|
||||||
|
require.Equal(t, "线上课程B", plan2.Name)
|
||||||
|
require.Equal(t, "elective", plan2.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 列表题库计数:仅统计未软删的关联题库,question_bank_count 随列表返回。
|
||||||
|
func TestListCourseLibraryQuestionBankCount(t *testing.T) {
|
||||||
|
svc, db, tenantID := newCourseLibraryFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "cl-banks", Name: "有两库课程", Mode: types.TrainingCourseModeOnline})
|
||||||
|
seedCourseLibraryItem(t, db, tenantID, &types.TrainingCourseLibrary{ID: "cl-deleted", Name: "仅软删库课程", Mode: types.TrainingCourseModeOnline})
|
||||||
|
deletedAt := timeNowPtr()
|
||||||
|
banks := []*types.TrainingQuestionBank{
|
||||||
|
{ID: "qb-1", TenantID: tenantID, LibraryCourseID: "cl-banks", Name: "题库1"},
|
||||||
|
{ID: "qb-2", TenantID: tenantID, LibraryCourseID: "cl-banks", Name: "题库2"},
|
||||||
|
{ID: "qb-3", TenantID: tenantID, LibraryCourseID: "cl-deleted", Name: "软删题库", DeletedAt: deletedAt},
|
||||||
|
// 其他课程的题库不应计入。
|
||||||
|
{ID: "qb-4", TenantID: tenantID, LibraryCourseID: "cl-other", Name: "别家题库"},
|
||||||
|
}
|
||||||
|
for _, b := range banks {
|
||||||
|
require.NoError(t, db.Create(b).Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
items, total, err := svc.ListCourseLibraryItems(ctx, tenantID, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.EqualValues(t, 2, total)
|
||||||
|
counts := map[string]int{}
|
||||||
|
for _, it := range items {
|
||||||
|
counts[it.ID] = it.QuestionBankCount
|
||||||
|
}
|
||||||
|
require.Equal(t, 2, counts["cl-banks"], fmt.Sprintf("计数结果: %v", counts))
|
||||||
|
require.Equal(t, 0, counts["cl-deleted"], "软删题库不应计入")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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,239 @@
|
|||||||
|
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"
|
||||||
|
"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("缺少回跳地址")
|
||||||
|
}
|
||||||
|
return client.BuildOAuthAuthorizeURL(redirectURI, token), 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 组装落地页载荷:课程/场次摘要 + 当前成员名单/重复标记。
|
||||||
|
func (s *trainingService) buildWecomCheckinPage(ctx context.Context, code *types.TrainingSignCode, member *types.TrainingMember, prevToken bool) (*types.WecomCheckinPage, error) {
|
||||||
|
// 姓名:档案 UserName 为联查字段,直查不回填;用平台账号显示名补齐,
|
||||||
|
// 落地页「工号 + 姓名」确认行展示(免登链路学员核对身份用)。
|
||||||
|
if 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),
|
||||||
|
}
|
||||||
|
// 名单/重复标记:前端提前渲染按钮态(置灰/已签到),提交时后端仍强校验兜底。
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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,91 @@ 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 还原落地页地址(反代透传 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/platform/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})
|
||||||
|
}
|
||||||
|
|
||||||
// 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"))
|
||||||
|
|||||||
@@ -66,9 +66,31 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
|
|||||||
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
||||||
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
|
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
|
||||||
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
|
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
|
||||||
|
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方
|
||||||
|
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护
|
||||||
|
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
|
||||||
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
|
||||||
|
// 调用方部门(id+名)用于适合人员匹配;无培训档案的调用方两个字段
|
||||||
|
// 留空(仅见「全部」与未设置适合人员的课程),不阻断目录查询。
|
||||||
|
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
|
||||||
|
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 {
|
||||||
|
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
|
||||||
|
}
|
||||||
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)
|
||||||
@@ -312,6 +334,20 @@ 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
|
||||||
|
// — 移除课程课件原始文件/知识库挂接(名称登记保留,课件变更即回待核验)。
|
||||||
|
func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
|
||||||
|
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c))
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||||
|
}
|
||||||
|
|
||||||
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
|
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
|
||||||
// 课件原始文件流(下载/在线预览)。
|
// 课件原始文件流(下载/在线预览)。
|
||||||
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
|
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -64,6 +64,11 @@ 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"},
|
||||||
// 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.
|
||||||
|
|||||||
@@ -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",
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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,16 @@ 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)
|
||||||
|
// 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 +112,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 +141,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 +181,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)
|
||||||
|
|||||||
@@ -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 /
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,13 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
|
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
|
||||||
@@ -42,6 +49,12 @@ 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)
|
||||||
|
// 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 +96,8 @@ 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)
|
||||||
|
// 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:发布/下线)。
|
||||||
@@ -102,6 +117,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 +144,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 +290,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 +300,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 需求提报表单下拉数据源(讲师/岗位)。
|
||||||
@@ -325,6 +354,8 @@ type TrainingService interface {
|
|||||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
|
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
|
||||||
// 已有文档作为课程课件(与上传同步同口径)。
|
// 已有文档作为课程课件(与上传同步同口径)。
|
||||||
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
|
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||||
|
// RemoveCourseLibraryMaterial 移除课程课件(文件/知识库挂接清空,名称登记保留)。
|
||||||
|
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, 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 +377,26 @@ 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)
|
||||||
|
|
||||||
// ---- 培训佐证文件(签到照/培训视频) ----
|
// ---- 培训佐证文件(签到照/培训视频) ----
|
||||||
// UploadSessionEvidence 上传线下课佐证:签到照/培训视频按 file_key 落对象存储。
|
// UploadSessionEvidence 上传线下课佐证:签到照/培训视频按 file_key 落对象存储。
|
||||||
@@ -426,6 +469,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)
|
||||||
|
|||||||
@@ -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
@@ -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"`
|
||||||
|
}
|
||||||
+85
-19
@@ -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 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
|
||||||
@@ -591,8 +595,9 @@ 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:''"`
|
// (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
|
||||||
|
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"`
|
||||||
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
|
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
|
||||||
Category string `json:"category" gorm:"type:varchar(64);default:''"`
|
Category string `json:"category" gorm:"type:varchar(64);default:''"`
|
||||||
// Type 类型(required 必修课/elective 选修课)。
|
// Type 类型(required 必修课/elective 选修课)。
|
||||||
@@ -632,6 +637,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"`
|
||||||
@@ -742,13 +749,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 +778,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 +791,58 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
// 培训佐证文件类型:签到照 / 培训视频。
|
// 培训佐证文件类型:签到照 / 培训视频。
|
||||||
const (
|
const (
|
||||||
TrainingEvidenceSignPhoto = "sign_photo"
|
TrainingEvidenceSignPhoto = "sign_photo"
|
||||||
|
|||||||
@@ -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 '';
|
||||||
@@ -136,6 +136,10 @@ build_app_image() {
|
|||||||
# 获取版本信息
|
# 获取版本信息
|
||||||
get_version_info
|
get_version_info
|
||||||
|
|
||||||
|
# 离线快速通道兜底:Dockerfile.app 无条件 COPY docker/prebuilt/,目录缺失的
|
||||||
|
# 构建机会直接失败;占位空目录让没有预构建产物的宿主机走回原全量构建路径
|
||||||
|
mkdir -p docker/prebuilt
|
||||||
|
|
||||||
docker build \
|
docker build \
|
||||||
--platform $PLATFORM \
|
--platform $PLATFORM \
|
||||||
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
|
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
|
||||||
|
|||||||
Reference in new issue
Block a user