Compare commits
22
Commits
3a20abc492
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f43fbef5db | ||
|
|
9950a28346 | ||
|
|
ea0524c445 | ||
|
|
11450bdb96 | ||
|
|
448fbcdaff | ||
|
|
8f225ecea9 | ||
|
|
196478114c | ||
|
|
42042ca8bd | ||
|
|
7e1e670f0a | ||
|
|
8bd02e7c7e | ||
|
|
4112de0703 | ||
|
|
6594f97e3c | ||
|
|
0819f8c4d1 | ||
|
|
3c8b595064 | ||
|
|
11ce1c3c0c | ||
|
|
80deef9c53 | ||
|
|
168057db78 | ||
|
|
27c4d96ae1 | ||
|
|
3f680882c8 | ||
|
|
a27d58560b | ||
|
|
3a578153bb | ||
|
|
4b899a4647 |
No files matched your search
@@ -659,6 +659,24 @@ SYSTEM_SIGNING_KEY=
|
||||
# 前置:Casdoor 应用 grantTypes 必须勾选 password(enablePassword 托管页开关与此无关,
|
||||
# 未勾选时登录返回 503「IdP 未开放 password grant」)。总开关 OIDC_AUTH_ENABLE 仍须为 true。
|
||||
# OIDC_AUTH_PASSWORD_LOGIN_ENABLED=false
|
||||
# Casdoor 管理 API(成员管理「同步CASDOOR成员」专用,000156):后端以 client_credentials
|
||||
# 换 token 后调 /api/get-users 拉全量用户自动开户/入空间。前置:Casdoor 应用 grantTypes
|
||||
# 必须勾选 Client Credentials,且凭据具备管理权限;未开启时同步接口返回 400 配置提示。
|
||||
# OIDC_AUTH_ADMIN_API_ENABLE=false
|
||||
# 管理端点基址,留空自动从 TokenEndpoint/IssuerURL 推导(scheme+host)。
|
||||
# OIDC_AUTH_ADMIN_BASE_URL=
|
||||
# get-users 的 owner 参数(Casdoor 组织名),留空 built-in。
|
||||
# OIDC_AUTH_ADMIN_ORGANIZATION=
|
||||
# 部门名称/编号取值字段(支持 a.b 点路径进 properties)。留空按内置候选顺序探测
|
||||
# (名称: department→dept→deptName→affiliation→title→organization→groups末段;
|
||||
# 编号: departmentCode→deptCode→dept_code→department_code→deptNo)。
|
||||
# OIDC_AUTH_ADMIN_DEPT_FIELD=
|
||||
# OIDC_AUTH_ADMIN_DEPT_CODE_FIELD=
|
||||
# 服务账号密码模式(推荐,优先于 client_credentials):部分 Casdoor 部署的 API
|
||||
# 鉴权(casbin)会拒绝 client_credentials 应用令牌调管理接口,此时改用目标组织
|
||||
# 管理员(is_admin)服务账号的 password grant。填用户名(不带组织前缀)与密码。
|
||||
# OIDC_AUTH_ADMIN_USERNAME=
|
||||
# OIDC_AUTH_ADMIN_PASSWORD=
|
||||
|
||||
|
||||
# #####################################################################
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# ai30 生产服自动部署
|
||||
# 触发:仅手动(workflow_dispatch)——生产环境人工卡点,push prod 不自动部署。
|
||||
# (发布纪律 standards://workflow/release@2.0.1:生产部署需人工触发;
|
||||
# 测试区走 deploy-hxtesting.yml 的 push test 触发,两者分工见 docs/deploy-hxtesting.md)
|
||||
# 执行:ai30 宿主上的 gitea-runner(label=deploy-ai30,host 模式,inspur 用户)
|
||||
# 说明:与 deploy-hxtesting 同构,差异三点——分支 prod、端口 8802、目标机 x86_64;
|
||||
# 端口登记:8801=测试(hxtesting) / 8802=生产(ai30),均属 88xx 平台 Web 号段。
|
||||
# 构建前产物 artifacts/ 与 .env 均为 gitignored,由部署管理员在 ai30 维护。
|
||||
name: deploy-ai30
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: deploy-ai30
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
DEPLOY_DIR: /data/ai-platform/ai_academy
|
||||
steps:
|
||||
- name: 同步代码
|
||||
run: |
|
||||
set -e
|
||||
cd "$DEPLOY_DIR"
|
||||
git fetch origin
|
||||
git checkout -q -B prod origin/prod
|
||||
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
|
||||
echo "当前部署提交: $(git log --oneline -1)"
|
||||
|
||||
- name: 构建镜像(app + frontend,x86_64 原生)
|
||||
run: |
|
||||
set -e
|
||||
cd "$DEPLOY_DIR"
|
||||
# WITH_ANYDOC=0:跳过 anydoc 解析引擎(Rust 工具链需外网;文档解析由 docreader 容器承担)
|
||||
WITH_ANYDOC=0 bash scripts/build_images.sh -p
|
||||
WITH_ANYDOC=0 bash scripts/build_images.sh -f
|
||||
docker tag wechatopenai/weknora-app:latest wechatopenai/weknora-app:sha-${GIT_SHA}
|
||||
docker tag wechatopenai/weknora-ui:latest wechatopenai/weknora-ui:sha-${GIT_SHA}
|
||||
# 仅清理本项目旧版本镜像(保留最近 5 个 sha-* 备回滚),不影响 ai30 上其他项目
|
||||
for repo in wechatopenai/weknora-app wechatopenai/weknora-ui; do
|
||||
docker images --format '{{.Tag}}' "$repo" | grep '^sha-' | tail -n +6 \
|
||||
| xargs -r -I{} docker rmi "$repo:{}" >/dev/null 2>&1 || true
|
||||
done
|
||||
|
||||
- name: 部署(compose up)
|
||||
run: |
|
||||
set -e
|
||||
cd "$DEPLOY_DIR"
|
||||
docker compose up -d --remove-orphans
|
||||
|
||||
- name: 健康检查
|
||||
run: |
|
||||
set -e
|
||||
sleep 20
|
||||
if curl -fsS -o /dev/null --max-time 10 http://127.0.0.1:8802/; then
|
||||
echo "WEB_OK: http://ai30:8802/ 已可访问 (sha-${GIT_SHA})"
|
||||
else
|
||||
echo "健康检查失败,容器状态:"
|
||||
cd "$DEPLOY_DIR" && docker compose ps
|
||||
exit 1
|
||||
fi
|
||||
@@ -22,9 +22,13 @@ jobs:
|
||||
set -e
|
||||
cd "$DEPLOY_DIR"
|
||||
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 log --oneline -1)"
|
||||
echo "同步后残留脏文件: $(git status --porcelain | wc -l) 项"
|
||||
|
||||
- name: 构建镜像(app + frontend,ARM64 原生)
|
||||
run: |
|
||||
|
||||
@@ -73,5 +73,10 @@ miniprogram/project.private.config.json
|
||||
# Locally built BrowserSkill runtime and extension bundles
|
||||
/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)
|
||||
tmp-extract-duckdb/
|
||||
.cgo-sqlite/
|
||||
+71
-8
@@ -17,13 +17,40 @@ RUN if [ -n "$APK_MIRROR_ARG" ]; then \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
ENV RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo
|
||||
ENV PATH=/usr/local/cargo/bin:$PATH
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
|
||||
COPY scripts/build_browserskill.sh scripts/browserskill-release.json ./scripts/
|
||||
# 离线快速通道:优先使用仓库内预构建产物(air-gapped/网络受限环境无需 clone GitHub)
|
||||
COPY artifacts/browserskill ./artifacts/browserskill/
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
RUN bash scripts/build_browserskill.sh /opt/academy/browserskill "${TARGETOS}/${TARGETARCH}"
|
||||
# 预构建产物存在时 Rust 工具链不需要(构建脚本走秒级快速通道)——此前无条件装
|
||||
# rustup 曾因 sh.rustup.rs 直连抖动反复失败拖慢全量构建。需要完整构建时才装,
|
||||
# 且走国内镜像链(与 anydoc 阶段一致),cargo/rustup 用 BuildKit 缓存挂载复用。
|
||||
# 注意:构建脚本本身必须始终执行——无产物时全量构建,有产物时也是它把产物
|
||||
# 复制进 /opt/academy/browserskill(最终 stage 的 COPY 依赖该路径)。
|
||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,id=bs-cargo-registry \
|
||||
--mount=type=cache,target=/usr/local/cargo/git,id=bs-cargo-git \
|
||||
--mount=type=cache,target=/usr/local/rustup,id=bs-rustup \
|
||||
if [ ! -f artifacts/browserskill/bsk ]; then \
|
||||
curl --http1.1 --proto '=https' --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh \
|
||||
-o /tmp/rustup-init.sh \
|
||||
|| curl --http1.1 --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
-o /tmp/rustup-init.sh; \
|
||||
ok=0; \
|
||||
for srv in https://rsproxy.cn https://mirrors.ustc.edu.cn/rust-static https://static.rust-lang.org; do \
|
||||
case "$srv" in \
|
||||
https://rsproxy.cn) upd=https://rsproxy.cn/rustup ;; \
|
||||
https://mirrors.ustc.edu.cn/rust-static) upd=https://mirrors.ustc.edu.cn/rust-static/rustup ;; \
|
||||
*) upd=https://static.rust-lang.org/rustup ;; \
|
||||
esac; \
|
||||
echo "==> Trying rust toolchain mirror: $srv"; \
|
||||
if RUSTUP_DIST_SERVER="$srv" RUSTUP_UPDATE_ROOT="$upd" \
|
||||
sh /tmp/rustup-init.sh -y --profile minimal --default-toolchain stable; then \
|
||||
ok=1; break; \
|
||||
fi; \
|
||||
done; \
|
||||
[ "$ok" = "1" ]; \
|
||||
fi && \
|
||||
bash scripts/build_browserskill.sh /opt/academy/browserskill "${TARGETOS}/${TARGETARCH}"
|
||||
|
||||
# Build stage
|
||||
FROM golang:1.26-bookworm AS builder
|
||||
@@ -48,14 +75,28 @@ RUN if [ -n "$APK_MIRROR_ARG" ]; then \
|
||||
apt-get update && \
|
||||
apt-get install -y git build-essential libsqlite3-dev curl
|
||||
|
||||
# Install migrate tool
|
||||
RUN go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
|
||||
# Install migrate tool(Go 模块缓存挂载:守护进程重启/层失效时不重新下载全量模块)
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
||||
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
|
||||
|
||||
# Copy go mod files. go.mod replace-points anydoc at ./third_party/anydoc-go,
|
||||
# so that module's go.mod must exist before `go mod download`.
|
||||
COPY go.mod go.sum ./
|
||||
COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod
|
||||
RUN go mod download
|
||||
# 离线快速通道(网络受限环境):docker/prebuilt/ 携带宿主机交叉编译的产物时,
|
||||
# 跳过 go mod download 等联网步骤,直接装填预构建二进制与 gojieba 运行时依赖。
|
||||
# 目录不入库(与 artifacts/browserskill 同口径),上游构建走下方原有路径不受影响。
|
||||
COPY docker/prebuilt/ /app/prebuilt/
|
||||
# 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖,
|
||||
# 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载)
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,id=go-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
|
||||
# DuckDB extensions (spatial/excel): prefer a local seed tarball exported from
|
||||
# a previously built image (artifacts/duckdb_extensions/seed.tar) —
|
||||
@@ -69,7 +110,13 @@ RUN if [ -s /tmp/duckdb-seed.tar ]; then \
|
||||
go run cmd/download/duckdb/duckdb.go; \
|
||||
fi
|
||||
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
|
||||
ARG VERSION_ARG
|
||||
@@ -119,12 +166,28 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \
|
||||
# the layer (~2.7 GB), which occupies disk locally and is uploaded to the CI
|
||||
# layer cache. Mounted, the cache lives outside the layer and repeated builds
|
||||
# reuse compiled objects instead of recompiling from scratch.
|
||||
RUN if [ "$WITH_ANYDOC" = "1" ]; then \
|
||||
#
|
||||
# 链接前剥离 anydoc 静态库的 LLVM LTO 段(.llvmbc/.llvmcmd/.llvm_ar 等):
|
||||
# golang:1.26-bookworm 浮动 tag 更新后的 Go 链接器拒绝所有 .llvm* 位码段;
|
||||
# fat 对象中的常规 ELF 代码段不受影响。必须在 anydoc 构建(生成 .a)之后、
|
||||
# make build-prod 之前,并按实际出现的段名逐个剥离。
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build,id=go-build \
|
||||
for a in $(find third_party/anydoc-go/lib -name '*.a' -type f); do \
|
||||
secs=$(readelf -S "$a" 2>/dev/null | grep -oE '\.llvm[A-Za-z0-9_.-]*' | sort -u); \
|
||||
for s in $secs; do \
|
||||
objcopy --remove-section "$s" "$a" || true; \
|
||||
done; \
|
||||
done; \
|
||||
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; \
|
||||
else \
|
||||
make build-prod; \
|
||||
fi
|
||||
RUN cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu/
|
||||
RUN cp -r /app/yanyiwu-mod/ /app/yanyiwu/
|
||||
|
||||
# Final stage
|
||||
FROM debian:12.12-slim
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# 生产服发布指南(ai30 手动部署)
|
||||
|
||||
> 面向本仓库的所有开发者。测试服流程见 [deploy-hxtesting.md](deploy-hxtesting.md);
|
||||
> 完整原理(runner 装法、踩坑、复建)见平台知识库
|
||||
> `sy-platform-knowledge/docs/ai-academy-gitea-actions自动部署指南.md`(生产侧照搬同构)。
|
||||
|
||||
## 一图流
|
||||
|
||||
```
|
||||
发布准备:git checkout prod
|
||||
git merge main ← 或从已验证的 test 内容合入
|
||||
git push origin prod ← 只进分支,不触发部署
|
||||
生产发布:Gitea → 仓库 → 工作流 → deploy-ai30 → 「运行工作流」(选 prod 分支)
|
||||
观察结果:工作流 tab 绿✅即发布完成(约 5-30 分钟,首次构建较慢)
|
||||
访问验证:http://192.168.100.230:8802 ← 工号 + 密码登录(正式 Casdoor auth.well-trust.com)
|
||||
```
|
||||
|
||||
## 你需要记住的三件事
|
||||
|
||||
1. **push prod 不自动部署(与测试区最大差异)**。生产环境人工卡点:把代码推上
|
||||
prod 分支只是「发布候选」,必须到工作流页面手动点「运行工作流」才会真正发布
|
||||
(发布纪律 `standards://workflow/release@2.0.1`:生产部署需人工触发)。
|
||||
2. **部署全自动**:手动触发后由 ai30 宿主 runner(label=deploy-ai30)构建镜像并
|
||||
compose up;失败点开红色运行记录看日志。回滚:ssh ai30 后
|
||||
`docker tag wechatopenai/weknora-app:sha-<旧hash> wechatopenai/weknora-app:latest`
|
||||
(ui 同理)→ `cd /data/ai-platform/ai_academy && docker compose up -d app frontend`。
|
||||
3. **服务器配置不随代码走**:`.env`(端口、数据库、正式 Casdoor 接入等)由部署管理员
|
||||
维护在 ai30 `/data/ai-platform/ai_academy/.env`(gitignored)。需要改配置找管理员。
|
||||
|
||||
## 与测试区的差异速查
|
||||
|
||||
| 项 | 测试区(hxtesting) | 生产区(ai30) |
|
||||
| --- | --- | --- |
|
||||
| 入口 | http://192.168.100.192:8801 | http://192.168.100.230:8802 |
|
||||
| 触发 | push `test` 分支即部署 | 手动运行 deploy-ai30 工作流 |
|
||||
| 工作流 | `.gitea/workflows/deploy-hxtesting.yml` | `.gitea/workflows/deploy-ai30.yml` |
|
||||
| runner | hxtesting 宿主 lisq 用户(deploy-host) | ai30 宿主 inspur 用户(deploy-ai30,linger 常驻) |
|
||||
| 认证 | 测试 Casdoor `autht.well-trust.com` | 正式 Casdoor `auth.well-trust.com`(应用 ai-academy) |
|
||||
| 工作目录 | `~/services/ai_academy` | `/data/ai-platform/ai_academy` |
|
||||
| 端口登记 | 8801(登记册 88xx 段) | 8802(app 容器仅回环 127.0.0.1:18080,宿主 8080 已被占用) |
|
||||
|
||||
## 环境信息速查
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| 生产服入口 | **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 |
|
||||
| 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) |
|
||||
| 认证 | 正式 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`(注册应用行)、`application_bak_20261120`(域名回调更新前) |
|
||||
| 数据落位 | 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 |
|
||||
| 流水线 | 仓库 → 工作流 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 代理后端) |
|
||||
@@ -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>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>AIDO</title>
|
||||
<title>和信智汇学院</title>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
|
||||
<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'))
|
||||
else MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||
// 会话已有效,无论 token 是否兑换成功都进入应用。
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
const handleGlobalOIDCCallback = async () => {
|
||||
|
||||
@@ -118,6 +118,8 @@ export interface UserInfo {
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
// 姓名/显示名(工号式账号的 username 是工号,界面展示姓名用;未设置为空串)
|
||||
display_name?: string
|
||||
tenant_id: string
|
||||
can_access_all_tenants?: boolean
|
||||
preferences?: UserPreferences
|
||||
@@ -158,6 +160,7 @@ export function userInfoFromApi(
|
||||
username: u?.username || '',
|
||||
email: u?.email || '',
|
||||
avatar: u?.avatar,
|
||||
display_name: u?.display_name || '',
|
||||
tenant_id: String(tid) || '',
|
||||
can_access_all_tenants: u?.can_access_all_tenants === true,
|
||||
is_system_admin: u?.is_system_admin === true,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
import type { WecomSyncSummary } from '@/api/training'
|
||||
|
||||
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
|
||||
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
|
||||
@@ -42,6 +43,8 @@ export interface OrgEmployee {
|
||||
post: string
|
||||
lecturer_rate: number
|
||||
status: string
|
||||
/** 企微账号(OA 同步/绑定维护;列表 Select org_employees.* 随行返回)。 */
|
||||
wecom_userid?: string
|
||||
/** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */
|
||||
user_name?: string
|
||||
dept_name?: string
|
||||
@@ -82,6 +85,10 @@ export interface OrgPlatformUser {
|
||||
email: string
|
||||
/** 姓名(OIDC displayName claim),可能为空 */
|
||||
display_name?: string
|
||||
/** Casdoor 同步的部门编号/名称(users.dept_code/dept_name,000156 同步态字段)。
|
||||
* 从平台用户添加时按 dept_code 自动预选组织架构部门;两者可为空。 */
|
||||
dept_code?: string
|
||||
dept_name?: string
|
||||
in_roster: boolean
|
||||
}
|
||||
|
||||
@@ -111,6 +118,64 @@ export interface OrgUpdateEmployee {
|
||||
export const updateEmployee = (id: string, payload: OrgUpdateEmployee) =>
|
||||
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) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
import { get, post, put, del, postUpload } from '@/utils/request'
|
||||
|
||||
// TenantRole mirrors internal/types/tenant_member.go's four-role enum.
|
||||
// Keep the string values aligned with the Go constants.
|
||||
@@ -14,6 +14,8 @@ export interface TenantMember {
|
||||
username: string
|
||||
/** 姓名:来自 OIDC 可配置 claim(默认 nickname),本地/工号账号可能为空 */
|
||||
display_name?: string
|
||||
/** 所属部门:Casdoor 同步回写 users.dept_name(000156 同步态字段),未同步为空 */
|
||||
dept_name?: string
|
||||
avatar?: string
|
||||
role: TenantRole
|
||||
status: TenantMemberStatus
|
||||
@@ -66,6 +68,71 @@ export interface SimpleResponse {
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** 批量导入单行结果,status ∈ added / created / exists / failed */
|
||||
export interface MemberImportRowResult {
|
||||
/** Excel 展示行号(从 1 起,含表头偏移) */
|
||||
row: number
|
||||
employee_no: string
|
||||
email: string
|
||||
name: string
|
||||
status: MemberImportRowStatus
|
||||
/** failed / exists 时的原因说明(后端已本地化为中文) */
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export type MemberImportRowStatus = 'added' | 'created' | 'exists' | 'failed'
|
||||
|
||||
export interface MemberImportResult {
|
||||
success: boolean
|
||||
data?: {
|
||||
total: number
|
||||
added: number
|
||||
created_accounts: number
|
||||
already_member: number
|
||||
failed: number
|
||||
results: MemberImportRowResult[]
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** Casdoor 同步单条跳过记录(工号/邮箱 + 原因,后端已本地化为中文) */
|
||||
export interface CasdoorSyncSkip {
|
||||
name: string
|
||||
email?: string
|
||||
reason: string
|
||||
}
|
||||
|
||||
/** 同步 CASDOOR 成员结果汇总(对应后端 types.CasdoorSyncResult) */
|
||||
export interface CasdoorSyncResult {
|
||||
casdoor_total: number
|
||||
users_created: number
|
||||
members_added: number
|
||||
members_existing: number
|
||||
depts_created: number
|
||||
/** 部门名称取自 Casdoor 的哪个字段;空 = 目录无部门数据,未同步部门 */
|
||||
dept_source?: string
|
||||
skipped?: CasdoorSyncSkip[]
|
||||
}
|
||||
|
||||
/** 同步 CASDOOR 成员接口响应(后端 gin.H 包裹 {success, data} 信封) */
|
||||
export interface CasdoorSyncResponse {
|
||||
success: boolean
|
||||
data?: CasdoorSyncResult
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步 CASDOOR 成员到当前空间:经 Casdoor 管理 API 拉全量用户,
|
||||
* 未注册自动开户、非成员以观察者加入;部门编号/名称随账号回写并
|
||||
* 对齐组织架构。单向增量幂等,不删除/不停用/不改已有成员角色。
|
||||
* Backend: POST /api/v1/tenants/:id/members/sync-casdoor (Owner+)。
|
||||
*/
|
||||
export async function syncCasdoorMembers(tenantId: number): Promise<CasdoorSyncResponse> {
|
||||
return (await post(
|
||||
`/api/v1/tenants/${tenantId}/members/sync-casdoor`,
|
||||
)) as unknown as CasdoorSyncResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页列出空间成员。
|
||||
* Backend: GET /api/v1/tenants/:id/members (Viewer+)。查询参数:`q`、`page`、`page_size`。
|
||||
@@ -153,3 +220,22 @@ export async function removeMember(
|
||||
export async function leaveTenant(tenantId: number): Promise<SimpleResponse> {
|
||||
return (await post(`/api/v1/tenants/${tenantId}/leave`)) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量导入空间成员(Excel 花名册,表头:工号/邮箱/姓名/角色)。
|
||||
* Backend: POST /api/v1/tenants/:id/members/import (Owner+, multipart file)。
|
||||
*
|
||||
* 逐行容错:单行失败不阻断整批,响应含逐行结果(status + reason),
|
||||
* 未注册员工由后端自动开户(随机密码、OIDC-only,首次登录自动收编)。
|
||||
*/
|
||||
export async function importMembers(
|
||||
tenantId: number,
|
||||
file: File,
|
||||
): Promise<MemberImportResult> {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
return (await postUpload(
|
||||
`/api/v1/tenants/${tenantId}/members/import`,
|
||||
form,
|
||||
)) as unknown as MemberImportResult
|
||||
}
|
||||
@@ -162,6 +162,8 @@ export interface TrainingDemand {
|
||||
dept_id: string
|
||||
submitter_id: string
|
||||
course_name: string
|
||||
/** 需求所填课程自动匹配的课程管理条目 id(000158:填报/导入时按名称精准匹配,未命中自动新增待核验课程) */
|
||||
library_course_id?: string
|
||||
/** 厂区(模板列:厂区,如 三厂) */
|
||||
plant: string
|
||||
/** 培训分类(模板列:分类,如 知识/技能/安全) */
|
||||
@@ -185,7 +187,7 @@ export interface TrainingDemand {
|
||||
check_status: 'pending' | 'passed' | 'fixed'
|
||||
check_msg: string
|
||||
status: string
|
||||
/** 联查展示字段:部门名称/讲师姓名/创建人姓名(提报人,联查 users 只读) */
|
||||
/** 部门名称(列表联查 org_depts 只读;导入载荷另携带 Excel「部门」列原始值,000158 后端据此做导入人部门归属校验) */
|
||||
dept_name?: string
|
||||
lecturer_name?: string
|
||||
submitter_name?: string
|
||||
@@ -458,12 +460,22 @@ export interface TrainingLibraryCourse {
|
||||
knowledge_id?: string
|
||||
/** 发布状态(000154):draft 草稿/published 已发布/offline 已下线 */
|
||||
publish_status?: string
|
||||
/** 核验状态(000157):pending 待核验/confirmed 已确认;发布前必须已确认 */
|
||||
verify_status?: string
|
||||
/** 核验人(课长/经理用户 id,联查展示用;仅审计) */
|
||||
confirmed_by?: string
|
||||
/** 核验时间 */
|
||||
confirmed_at?: string
|
||||
/** 移除课件文件标记(保存时置 true 强制清空文件) */
|
||||
clear_file?: boolean
|
||||
/** 讲师姓名(联查 users 只读) */
|
||||
lecturer_name?: string
|
||||
/** 创建人用户 id(学员「与我相关」列表的编辑权限判断用) */
|
||||
creator_id?: string
|
||||
/** 创建人姓名(联查 users 只读;导入/新增时落 creator_id 后带出) */
|
||||
creator_name?: string
|
||||
/** 关联题库数(联查只读;列表「试题」有/无展示) */
|
||||
question_bank_count?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@@ -485,6 +497,10 @@ export const publishCourseLibraryItem = (id: string) =>
|
||||
export const offlineCourseLibraryItem = (id: string) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(`${base}/course-library/${enc(id)}/offline`)
|
||||
|
||||
/** 课程条目核验(000157,单个/批量共用):仅课长/经理限本部门;返回核验/跳过条数。 */
|
||||
export const verifyCourseLibraryItems = (ids: string[]) =>
|
||||
post<{ success: boolean; data: { verified: number; skipped: number } }>(`${base}/course-library/verify`, { ids })
|
||||
|
||||
/** 批量导入(前端解析 Excel 后逐行提交,与需求导入同口径;返回导入条数)。 */
|
||||
export const importCourseLibrary = (items: Partial<TrainingLibraryCourse>[]) =>
|
||||
post<{ success: boolean; data: { imported: number } }>(`${base}/course-library/import`, { items })
|
||||
@@ -512,6 +528,12 @@ export const attachCourseLibraryMaterialFromKb = (id: string, payload: { knowled
|
||||
export const downloadCourseLibraryMaterial = (id: string) =>
|
||||
getDown(`${base}/course-library/${enc(id)}/material/file`)
|
||||
|
||||
/** 移除课件原始文件/知识库挂接(名称登记保留;课件变更即回待核验)。 */
|
||||
export const removeCourseLibraryMaterial = (id: string) =>
|
||||
post<{ success: boolean; data: TrainingLibraryCourse }>(
|
||||
`${base}/course-library/${enc(id)}/material/remove`,
|
||||
)
|
||||
|
||||
export const listSessions = (query?: ListQuery) =>
|
||||
get<{ success: boolean; data: TrainingCourseSession[] }>(`${base}/sessions`, { params: query })
|
||||
|
||||
@@ -625,13 +647,69 @@ export const createSignCode = (
|
||||
export const getSignCode = (sessionId: string) =>
|
||||
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`, {
|
||||
token,
|
||||
lat,
|
||||
lng,
|
||||
channel,
|
||||
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) =>
|
||||
@@ -956,6 +1034,10 @@ export const saveLearningProgress = (taskId: string, materialId: string, positio
|
||||
export const listMyLearningTasks = () =>
|
||||
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 {
|
||||
employee_no?: string
|
||||
@@ -1298,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_CONTENT =
|
||||
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
|
||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录和信智汇学院 → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||
|
||||
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
|
||||
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
<span v-else class="avatar-placeholder">{{ userInitial }}</span>
|
||||
</div>
|
||||
<div v-if="!showCollapsedLayout" class="user-info">
|
||||
<!-- 多空间 / superuser:首行空间名,次行 username · 角色。单空间:昵称 + 邮箱。 -->
|
||||
<!-- 多空间 / superuser:首行空间名,次行 姓名(未设置回落账号) · 角色。单空间:账号 + 姓名(未设置回落邮箱)。 -->
|
||||
<template v-if="showTenantIdentityLine">
|
||||
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
|
||||
<div class="user-tenant-meta">
|
||||
<span v-if="userName && userName !== activeTenantName" class="user-tenant-meta-name">{{ userName }}</span>
|
||||
<span v-if="(userName && userName !== activeTenantName) && currentRoleLabel"
|
||||
<span v-if="userDisplayLabel && userDisplayLabel !== activeTenantName" class="user-tenant-meta-name">{{ userDisplayLabel }}</span>
|
||||
<span v-if="(userDisplayLabel && userDisplayLabel !== activeTenantName) && currentRoleLabel"
|
||||
class="user-tenant-meta-sep">·</span>
|
||||
<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>
|
||||
@@ -21,7 +21,7 @@
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="user-name">{{ userName }}</div>
|
||||
<div class="user-email">{{ userEmail }}</div>
|
||||
<div class="user-email">{{ userDisplayName }}</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -67,7 +67,7 @@
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
<span v-if="userEmail" class="dropdown-user-email">{{ userEmail }}</span>
|
||||
<span v-if="userDisplayName" class="dropdown-user-email">{{ userDisplayName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -198,6 +198,7 @@ const menuVisible = ref(false)
|
||||
const userInfo = computed(() => ({
|
||||
username: authStore.user?.username || t('common.defaultUser'),
|
||||
email: authStore.user?.email || 'user@example.com',
|
||||
displayName: authStore.user?.display_name || '',
|
||||
avatar: authStore.user?.avatar || '',
|
||||
}))
|
||||
|
||||
@@ -205,9 +206,16 @@ const userName = computed(() => userInfo.value.username)
|
||||
const userEmail = computed(() => userInfo.value.email)
|
||||
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(() => {
|
||||
return userName.value.charAt(0).toUpperCase()
|
||||
return userDisplayLabel.value.charAt(0).toUpperCase()
|
||||
})
|
||||
|
||||
// 切换菜单显示
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// ===== AIDO 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
||||
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入
|
||||
// ===== 和信智汇学院 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
||||
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入。
|
||||
// 品牌名由「AIDO」更名而来:中文六个字,字号/字距相应收窄以适配
|
||||
// 260px 展开侧栏(logo 与搜索/折叠图标同行)与登录页左上角。
|
||||
.aido-logo {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@@ -16,12 +18,12 @@
|
||||
}
|
||||
|
||||
&__text {
|
||||
font-family: 'Trebuchet MS', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
font-size: 27px;
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', sans-serif;
|
||||
font-size: 19px;
|
||||
line-height: 1.15;
|
||||
font-weight: 800;
|
||||
font-style: italic;
|
||||
letter-spacing: 2.5px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
letter-spacing: 1px;
|
||||
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(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%);
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
<div class="aside_rail">
|
||||
<!-- 展开时:Logo + 搜索/折叠按钮同行 -->
|
||||
<div class="logo_row" v-if="!uiStore.sidebarCollapsed">
|
||||
<div class="logo_box" @click="router.push('/platform/knowledge-bases')" style="cursor: pointer;">
|
||||
<span class="aido-logo" aria-label="AIDO" title="AIDO">
|
||||
<span class="aido-logo__text">AIDO</span>
|
||||
<div class="logo_box" @click="router.push('/platform/creatChat')" style="cursor: pointer;">
|
||||
<span class="aido-logo" aria-label="和信智汇学院" title="和信智汇学院">
|
||||
<span class="aido-logo__text">和信智汇学院</span>
|
||||
<span class="aido-logo__dot"></span>
|
||||
</span>
|
||||
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
|
||||
@@ -605,12 +605,12 @@ const moreToolItems = computed<MenuItem[]>(() => {
|
||||
const items = MORE_TOOLS_ORDER
|
||||
.map(path => all.find((item: MenuItem) => item.path === path))
|
||||
.filter((item): item is MenuItem => !!item);
|
||||
// 末位固定追加「配置中心」「职称角色」「组织架构」;「共享空间」还原至最底
|
||||
// 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底
|
||||
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
|
||||
// 职称角色(000159):自「企业培训」分组迁入,置于配置中心之后
|
||||
const MEMBERS_TOOL_ITEM: MenuItem = { title: '职称角色', icon: 'training', path: 'training/members' };
|
||||
// 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由
|
||||
// /platform/training/members 由路由重定向兜底
|
||||
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_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 = () => {
|
||||
trainingOpen.value = !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;
|
||||
};
|
||||
|
||||
// 「更多工具」分组展开状态(记忆用户偏好,默认展开)
|
||||
// 「更多工具」分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
|
||||
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 = () => {
|
||||
moreToolsOpen.value = !moreToolsOpen.value;
|
||||
localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value));
|
||||
|
||||
@@ -2970,7 +2970,7 @@ export default {
|
||||
haveAccount: 'Already have an account?',
|
||||
backToLogin: 'Back to Login',
|
||||
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',
|
||||
registerFailed: 'Registration failed',
|
||||
subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade',
|
||||
@@ -8517,6 +8517,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: 'Employee ID & email',
|
||||
deptName: 'Department',
|
||||
displayName: 'Name',
|
||||
role: 'Role',
|
||||
joinedAt: 'Joined',
|
||||
@@ -8535,6 +8536,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: 'Role'
|
||||
},
|
||||
import: {
|
||||
button: 'Bulk Import',
|
||||
dialogTitle: 'Bulk Import Members',
|
||||
resultTitle: 'Import Result',
|
||||
description: 'Add members in bulk from an Excel roster: download the template, fill in employee ID, name, department, email and role, then upload it back. Members without an existing account are provisioned automatically and join this workspace right away. Departments are auto-matched against the departments maintained in Department Management; unmatched values are left blank.',
|
||||
downloadTemplate: 'Download Template',
|
||||
pickFile: 'Click to choose an Excel file',
|
||||
fileHint: 'Supports .xlsx / .xls; headers: employee ID, name, department, email, role',
|
||||
repick: 'Click to choose a different file',
|
||||
submit: 'Start Import',
|
||||
invalidFileType: 'Please choose an .xlsx or .xls Excel file',
|
||||
summaryAdded: 'Added',
|
||||
summaryCreated: 'Accounts created',
|
||||
summaryExists: 'Already members',
|
||||
summaryFailed: 'Failed',
|
||||
failedListTitle: 'Failed rows',
|
||||
rowLabel: 'Row {row}',
|
||||
reimport: 'Import again'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: 'Sync CASDOOR members',
|
||||
dialogTitle: 'Sync CASDOOR members',
|
||||
resultTitle: 'Sync result',
|
||||
description: 'Pull registered users from CASDOOR automatically: new users get an account and join this workspace as viewers; existing members keep their roles. Department codes/names are synced into the org structure. Nothing is deleted or disabled.',
|
||||
confirm: 'Start sync',
|
||||
failed: 'Sync failed',
|
||||
summaryTotal: 'CASDOOR users',
|
||||
summaryCreated: 'New accounts',
|
||||
summaryAdded: 'Newly joined',
|
||||
summaryExists: 'Already members',
|
||||
summaryDepts: 'New departments',
|
||||
skippedListTitle: 'Skipped',
|
||||
skippedEmpty: 'All users processed, nothing skipped.',
|
||||
deptSourceHint: 'Department source field: {field}',
|
||||
noDeptHint: 'CASDOOR users have no department data yet; only members were synced. Sync again after department fields are enabled.',
|
||||
done: 'Sync finished'
|
||||
},
|
||||
remove: {
|
||||
button: 'Remove',
|
||||
confirmBody: 'Are you sure you want to remove {name} from this workspace? They will lose access immediately.',
|
||||
|
||||
@@ -2970,7 +2970,7 @@ export default {
|
||||
haveAccount: 'すでにアカウントをお持ちですか?',
|
||||
backToLogin: 'ログインに戻る',
|
||||
loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。',
|
||||
firstTime: 'AIDOは初めてですか?',
|
||||
firstTime: '和信智汇学院は初めてですか?',
|
||||
registerSuccess: '登録が完了しました。ログインしてください',
|
||||
registerFailed: '登録に失敗しました',
|
||||
subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード',
|
||||
@@ -8517,6 +8517,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: '従業員IDとメールアドレス',
|
||||
deptName: '部署',
|
||||
displayName: '氏名',
|
||||
role: 'ロール',
|
||||
joinedAt: '参加日時',
|
||||
@@ -8535,6 +8536,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: 'ロール'
|
||||
},
|
||||
import: {
|
||||
button: '一括インポート',
|
||||
dialogTitle: 'メンバーの一括インポート',
|
||||
resultTitle: 'インポート結果',
|
||||
description: 'Excel テンプレートでメンバーを一括追加します。テンプレートをダウンロードして社員番号・氏名・部署・メールアドレス・ロールを記入し、アップロードしてください。未登録のメンバーはアカウントが自動作成され、このワークスペースにすぐ追加されます(初回ログイン時に紐付け)。部署は部署管理で登録済みの部署と自動照合され、一致しない場合は空欄になります。',
|
||||
downloadTemplate: 'テンプレートをダウンロード',
|
||||
pickFile: 'クリックして Excel ファイルを選択',
|
||||
fileHint: '.xlsx / .xls 対応。ヘッダー:社員番号・氏名・部署・メールアドレス・ロール',
|
||||
repick: 'クリックしてファイルを再選択',
|
||||
submit: 'インポート開始',
|
||||
invalidFileType: '.xlsx または .xls 形式の Excel ファイルを選択してください',
|
||||
summaryAdded: '追加完了',
|
||||
summaryCreated: 'アカウント作成',
|
||||
summaryExists: '既にメンバー',
|
||||
summaryFailed: '失敗',
|
||||
failedListTitle: '失敗明細',
|
||||
rowLabel: '{row} 行目',
|
||||
reimport: '再インポート'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: 'CASDOORメンバー同期',
|
||||
dialogTitle: 'CASDOORメンバー同期',
|
||||
resultTitle: '同期結果',
|
||||
description: 'CASDOORから登録済みユーザーを自動取得します。未登録のユーザーはアカウントを作成して閲覧者として参加し、既存メンバーのロールは変更されません。部署コード・部署名も組織図に同期されます。削除・無効化は行いません。',
|
||||
confirm: '同期開始',
|
||||
failed: '同期に失敗しました',
|
||||
summaryTotal: 'CASDOORユーザー',
|
||||
summaryCreated: '新規アカウント',
|
||||
summaryAdded: '新規参加',
|
||||
summaryExists: '既存メンバー',
|
||||
summaryDepts: '新規部署',
|
||||
skippedListTitle: 'スキップ明細',
|
||||
skippedEmpty: '全ユーザー処理完了、スキップなし。',
|
||||
deptSourceHint: '部署ソースフィールド: {field}',
|
||||
noDeptHint: 'CASDOORユーザーに部署データがありません。メンバーのみ同期しました。部署フィールド有効化後に再同期してください。',
|
||||
done: '同期完了'
|
||||
},
|
||||
remove: {
|
||||
button: '削除',
|
||||
confirmBody: '{name}をこのワークスペースから削除してもよろしいですか?このユーザはすぐにアクセスできなくなります。',
|
||||
|
||||
@@ -692,6 +692,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: '역할'
|
||||
},
|
||||
import: {
|
||||
button: '일괄 가져오기',
|
||||
dialogTitle: '구성원 일괄 가져오기',
|
||||
resultTitle: '가져오기 결과',
|
||||
description: 'Excel 템플릿으로 구성원을 일괄 추가합니다. 템플릿을 다운로드해 사원번호, 이름, 부서, 이메일, 역할을 작성한 뒤 업로드하세요. 아직 가입하지 않은 구성원은 계정이 자동 생성되어 현재 스페이스에 바로 추가되며, 첫 로그인 시 자동으로 연결됩니다. 부서는 부서 관리에 등록된 부서와 자동으로 일치되며, 일치하지 않으면 비워 둡니다.',
|
||||
downloadTemplate: '템플릿 다운로드',
|
||||
pickFile: '클릭하여 Excel 파일 선택',
|
||||
fileHint: '.xlsx / .xls 지원, 헤더: 사원번호, 이름, 부서, 이메일, 역할',
|
||||
repick: '클릭하여 파일 다시 선택',
|
||||
submit: '가져오기 시작',
|
||||
invalidFileType: '.xlsx 또는 .xls 형식의 Excel 파일을 선택해 주세요',
|
||||
summaryAdded: '추가 완료',
|
||||
summaryCreated: '계정 생성',
|
||||
summaryExists: '이미 구성원',
|
||||
summaryFailed: '실패',
|
||||
failedListTitle: '실패 상세',
|
||||
rowLabel: '{row}행',
|
||||
reimport: '다시 가져오기'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: 'CASDOOR 구성원 동기화',
|
||||
dialogTitle: 'CASDOOR 구성원 동기화',
|
||||
resultTitle: '동기화 결과',
|
||||
description: 'CASDOOR에서 가입된 사용자를 자동으로 가져옵니다. 신규 사용자는 계정이 생성되어 뷰어로 합류하고, 기존 구성원의 역할은 유지됩니다. 부서 코드/부서명도 조직도에 동기화됩니다. 삭제나 비활성화는 하지 않습니다.',
|
||||
confirm: '동기화 시작',
|
||||
failed: '동기화 실패',
|
||||
summaryTotal: 'CASDOOR 사용자',
|
||||
summaryCreated: '신규 계정',
|
||||
summaryAdded: '신규 합류',
|
||||
summaryExists: '기존 구성원',
|
||||
summaryDepts: '신규 부서',
|
||||
skippedListTitle: '제외 내역',
|
||||
skippedEmpty: '전체 사용자 처리 완료, 제외 없음.',
|
||||
deptSourceHint: '부서 소스 필드: {field}',
|
||||
noDeptHint: 'CASDOOR 사용자에게 부서 데이터가 없어 구성원만 동기화했습니다. 부서 필드 활성화 후 다시 동기화하세요.',
|
||||
done: '동기화 완료'
|
||||
},
|
||||
role: {
|
||||
owner: '소유자',
|
||||
admin: '관리자',
|
||||
@@ -700,6 +737,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: '사원번호와 이메일',
|
||||
deptName: '부서',
|
||||
displayName: '이름',
|
||||
role: '역할',
|
||||
joinedAt: '가입일',
|
||||
@@ -6224,7 +6262,7 @@ export default {
|
||||
haveAccount: '이미 계정이 있으신가요?',
|
||||
backToLogin: '로그인으로 돌아가기',
|
||||
loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.',
|
||||
firstTime: 'AIDO가 처음이신가요?',
|
||||
firstTime: '和信智汇学院이 처음이신가요?',
|
||||
registerSuccess: '가입이 완료되었습니다. 로그인해주세요',
|
||||
registerFailed: '가입 실패',
|
||||
subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드',
|
||||
|
||||
@@ -692,6 +692,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: 'Роль'
|
||||
},
|
||||
import: {
|
||||
button: 'Массовый импорт',
|
||||
dialogTitle: 'Массовое добавление участников',
|
||||
resultTitle: 'Результат импорта',
|
||||
description: 'Добавляйте участников массово через Excel-шаблон: скачайте шаблон, заполните табельный номер, имя, отдел, email и роль, затем загрузите файл. Ещё не зарегистрированные сотрудники получат учётные записи автоматически и сразу войдут в текущее пространство. Отделы автоматически сопоставляются с отделами, заведёнными в управлении отделами; без совпадения поле останется пустым.',
|
||||
downloadTemplate: 'Скачать шаблон',
|
||||
pickFile: 'Нажмите, чтобы выбрать файл Excel',
|
||||
fileHint: 'Поддерживаются .xlsx / .xls; заголовки: табельный номер, имя, отдел, email, роль',
|
||||
repick: 'Нажмите, чтобы выбрать другой файл',
|
||||
submit: 'Начать импорт',
|
||||
invalidFileType: 'Выберите файл Excel формата .xlsx или .xls',
|
||||
summaryAdded: 'Добавлено',
|
||||
summaryCreated: 'Создано аккаунтов',
|
||||
summaryExists: 'Уже участники',
|
||||
summaryFailed: 'С ошибками',
|
||||
failedListTitle: 'Ошибочные строки',
|
||||
rowLabel: 'Строка {row}',
|
||||
reimport: 'Импортировать снова'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: 'Синхронизация CASDOOR',
|
||||
dialogTitle: 'Синхронизация участников CASDOOR',
|
||||
resultTitle: 'Результат синхронизации',
|
||||
description: 'Автоматически загружает пользователей из CASDOOR: новые получают учётную запись и присоединяются как наблюдатели; роли существующих участников не меняются. Коды и названия отделов синхронизируются в организационную структуру. Ничего не удаляется и не отключается.',
|
||||
confirm: 'Начать синхронизацию',
|
||||
failed: 'Ошибка синхронизации',
|
||||
summaryTotal: 'Пользователи CASDOOR',
|
||||
summaryCreated: 'Новые учётные записи',
|
||||
summaryAdded: 'Новые участники',
|
||||
summaryExists: 'Уже участники',
|
||||
summaryDepts: 'Новые отделы',
|
||||
skippedListTitle: 'Пропущено',
|
||||
skippedEmpty: 'Все пользователи обработаны, пропусков нет.',
|
||||
deptSourceHint: 'Поле источника отдела: {field}',
|
||||
noDeptHint: 'У пользователей CASDOOR нет данных об отделах — синхронизированы только участники. Повторите после включения полей отделов.',
|
||||
done: 'Синхронизация завершена'
|
||||
},
|
||||
role: {
|
||||
owner: 'Владелец',
|
||||
admin: 'Администратор',
|
||||
@@ -700,6 +737,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: 'Табельный номер и email',
|
||||
deptName: 'Отдел',
|
||||
displayName: 'Имя',
|
||||
role: 'Роль',
|
||||
joinedAt: 'Дата вступления',
|
||||
@@ -6224,7 +6262,7 @@ export default {
|
||||
haveAccount: 'Уже есть аккаунт?',
|
||||
backToLogin: 'Вернуться ко входу',
|
||||
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
|
||||
firstTime: 'Впервые в AIDO?',
|
||||
firstTime: 'Впервые в 和信智汇学院?',
|
||||
registerSuccess: 'Регистрация завершена. Войдите в систему',
|
||||
registerFailed: 'Ошибка регистрации',
|
||||
subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ',
|
||||
|
||||
@@ -692,6 +692,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: '角色'
|
||||
},
|
||||
import: {
|
||||
button: '批量导入',
|
||||
dialogTitle: '批量导入成员',
|
||||
resultTitle: '导入结果',
|
||||
description: '按 Excel 模板批量加入成员:先下载模板填写工号、姓名、部门、邮箱与角色,再上传导入。尚未注册的员工会自动创建账号并加入当前空间,首次登录后自动关联。部门会按部门管理中已维护的部门自动匹配,未匹配到时留空。',
|
||||
downloadTemplate: '下载模板',
|
||||
pickFile: '点击选择 Excel 文件',
|
||||
fileHint: '支持 .xlsx / .xls,表头:工号、姓名、部门、邮箱、角色',
|
||||
repick: '点击可重新选择文件',
|
||||
submit: '开始导入',
|
||||
invalidFileType: '请选择 .xlsx 或 .xls 格式的 Excel 文件',
|
||||
summaryAdded: '成功加入',
|
||||
summaryCreated: '新建账号',
|
||||
summaryExists: '已是成员',
|
||||
summaryFailed: '失败',
|
||||
failedListTitle: '失败明细',
|
||||
rowLabel: '第 {row} 行',
|
||||
reimport: '重新导入'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: '同步CASDOOR成员',
|
||||
dialogTitle: '同步CASDOOR成员',
|
||||
resultTitle: '同步结果',
|
||||
description: '从 CASDOOR 自动拉取已注册用户:尚未建档的自动创建账号并以访客加入当前空间,已有成员保持角色不变;同时同步部门编号/名称到组织架构。不会删除或停用任何成员。',
|
||||
confirm: '开始同步',
|
||||
failed: '同步失败',
|
||||
summaryTotal: 'CASDOOR 用户',
|
||||
summaryCreated: '新建账号',
|
||||
summaryAdded: '新加入',
|
||||
summaryExists: '已是成员',
|
||||
summaryDepts: '新建部门',
|
||||
skippedListTitle: '跳过明细',
|
||||
skippedEmpty: '全部用户处理成功,无跳过。',
|
||||
deptSourceHint: '部门来源字段:{field}',
|
||||
noDeptHint: 'CASDOOR 用户暂无部门数据,仅同步成员;开通部门字段后再次同步即可带入。',
|
||||
done: '同步完成'
|
||||
},
|
||||
role: {
|
||||
owner: '所有者',
|
||||
admin: '管理员',
|
||||
@@ -700,6 +737,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: '工号与邮箱',
|
||||
deptName: '所属部门',
|
||||
displayName: '姓名',
|
||||
role: '角色',
|
||||
joinedAt: '加入时间',
|
||||
@@ -6225,7 +6263,7 @@ export default {
|
||||
haveAccount: '已有账户?',
|
||||
backToLogin: '返回登录',
|
||||
loginHint: '登录以继续使用;首次使用请在下方创建账户。',
|
||||
firstTime: '首次使用 AIDO?',
|
||||
firstTime: '首次使用 和信智汇学院?',
|
||||
registerSuccess: '注册成功,请登录',
|
||||
registerFailed: '注册失败',
|
||||
subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级',
|
||||
|
||||
@@ -692,6 +692,43 @@ export default {
|
||||
emailPlaceholder: 'invitee{\'@\'}example.com',
|
||||
roleLabel: '角色'
|
||||
},
|
||||
import: {
|
||||
button: '批次匯入',
|
||||
dialogTitle: '批次匯入成員',
|
||||
resultTitle: '匯入結果',
|
||||
description: '依 Excel 範本批次加入成員:先下載範本填寫工號、姓名、部門、電子信箱與角色,再上傳匯入。尚未註冊的員工會自動建立帳號並加入目前空間,首次登入後自動關聯。部門會按部門管理中已維護的部門自動比對,未比對到時留空。',
|
||||
downloadTemplate: '下載範本',
|
||||
pickFile: '點擊選擇 Excel 檔案',
|
||||
fileHint: '支援 .xlsx / .xls,表頭:工號、姓名、部門、電子信箱、角色',
|
||||
repick: '點擊可重新選擇檔案',
|
||||
submit: '開始匯入',
|
||||
invalidFileType: '請選擇 .xlsx 或 .xls 格式的 Excel 檔案',
|
||||
summaryAdded: '成功加入',
|
||||
summaryCreated: '新建帳號',
|
||||
summaryExists: '已是成員',
|
||||
summaryFailed: '失敗',
|
||||
failedListTitle: '失敗明細',
|
||||
rowLabel: '第 {row} 列',
|
||||
reimport: '重新匯入'
|
||||
},
|
||||
syncCasdoor: {
|
||||
button: '同步CASDOOR成員',
|
||||
dialogTitle: '同步CASDOOR成員',
|
||||
resultTitle: '同步結果',
|
||||
description: '從 CASDOOR 自動拉取已註冊使用者:尚未建檔的自動建立帳號並以訪客加入目前空間,已有成員保持角色不變;同時同步部門編號/名稱到組織架構。不會刪除或停用任何成員。',
|
||||
confirm: '開始同步',
|
||||
failed: '同步失敗',
|
||||
summaryTotal: 'CASDOOR 使用者',
|
||||
summaryCreated: '新建帳號',
|
||||
summaryAdded: '新加入',
|
||||
summaryExists: '已是成員',
|
||||
summaryDepts: '新建部門',
|
||||
skippedListTitle: '略過明細',
|
||||
skippedEmpty: '全部使用者處理成功,無略過。',
|
||||
deptSourceHint: '部門來源欄位:{field}',
|
||||
noDeptHint: 'CASDOOR 使用者暫無部門資料,僅同步成員;開通部門欄位後再次同步即可帶入。',
|
||||
done: '同步完成'
|
||||
},
|
||||
role: {
|
||||
owner: '所有者',
|
||||
admin: '管理員',
|
||||
@@ -700,6 +737,7 @@ export default {
|
||||
},
|
||||
columns: {
|
||||
member: '工號與郵箱',
|
||||
deptName: '所屬部門',
|
||||
displayName: '姓名',
|
||||
role: '角色',
|
||||
joinedAt: '加入時間',
|
||||
@@ -6225,7 +6263,7 @@ export default {
|
||||
haveAccount: '已有帳戶?',
|
||||
backToLogin: '返回登入',
|
||||
loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。',
|
||||
firstTime: '首次使用 AIDO?',
|
||||
firstTime: '首次使用 和信智汇学院?',
|
||||
registerSuccess: '註冊成功,請登入',
|
||||
registerFailed: '註冊失敗',
|
||||
subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級',
|
||||
|
||||
@@ -27,6 +27,7 @@ function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
|
||||
to.path === '/' ||
|
||||
to.path === '/platform' ||
|
||||
to.path === '/platform/knowledge-bases' ||
|
||||
to.path === '/platform/creatChat' ||
|
||||
to.name === 'knowledgeBaseList'
|
||||
)
|
||||
}
|
||||
@@ -46,7 +47,8 @@ const router = createRouter({
|
||||
routes: [
|
||||
{
|
||||
path: "/",
|
||||
redirect: "/platform/knowledge-bases",
|
||||
// 登录用户默认打开 AI 对话页(首页口径,与登录成功跳转一致)
|
||||
redirect: "/platform/creatChat",
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
@@ -94,7 +96,7 @@ const router = createRouter({
|
||||
{
|
||||
path: "/platform",
|
||||
name: "Platform",
|
||||
redirect: "/platform/knowledge-bases",
|
||||
redirect: "/platform/creatChat",
|
||||
component: () => import("../views/platform/index.vue"),
|
||||
meta: { requiresInit: true, requiresAuth: true },
|
||||
children: [
|
||||
@@ -156,12 +158,18 @@ const router = createRouter({
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
{
|
||||
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/职称角色/配置中心)
|
||||
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/配置中心)
|
||||
// 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。
|
||||
path: "training",
|
||||
name: "training",
|
||||
redirect: "/platform/training/dashboard"
|
||||
},
|
||||
{
|
||||
// 职称角色页已并入「组织架构」页维护(员工/角色/企微账号一处维护),
|
||||
// 旧链接与书签兜底重定向。
|
||||
path: "training/members",
|
||||
redirect: "/platform/org-center"
|
||||
},
|
||||
{
|
||||
path: "training/:tab",
|
||||
name: "trainingTab",
|
||||
@@ -177,11 +185,14 @@ const router = createRouter({
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
{
|
||||
// 学员扫码签到页:培训签到页二维码落地页,携 token 自动定位并签到(需登录态)。
|
||||
// 学员扫码签到落地页(2026-11 企微扫码免登):企微「扫一扫」直接打开,
|
||||
// 页面内自行完成免登(OAuth 静默授权)/自动登录/倒计时/点击签到,
|
||||
// 故显式 requiresAuth:false + requiresInit:false 放行路由守卫
|
||||
// (meta 缺省 = undefined 时守卫仍按需登录拦截,必须显式 false)。
|
||||
path: "training/checkin/:token",
|
||||
name: "trainingCheckin",
|
||||
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) {
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
@@ -377,9 +388,9 @@ router.beforeEach(async (to, from, next) => {
|
||||
|
||||
// 如果访问的是登录页面或初始化页面,直接放行
|
||||
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
|
||||
// 如果已登录用户访问登录页面,重定向到知识库列表页面
|
||||
// 如果已登录用户访问登录页面,重定向到首页(AI 对话)
|
||||
if (to.path === '/login' && authStore.isLoggedIn) {
|
||||
next(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
next(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||
return
|
||||
}
|
||||
next()
|
||||
@@ -431,7 +442,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined
|
||||
if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) {
|
||||
MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable'))
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -441,7 +452,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
// the bounce. This is UI-only; the server enforces the real check.
|
||||
if (to.meta.requiresSystemAdmin === true) {
|
||||
if (!authStore.isSystemAdmin) {
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,9 +165,9 @@ export const TRAINING_MOCK = {
|
||||
|
||||
// 课程管理(课程资产主数据):预览 harness 演示数据(编号 CRS-#### 与后端一致)
|
||||
const COURSE_LIBRARY_MOCK = [
|
||||
{ id: 'lib-1', code: 'CRS-0001', name: '新员工入职通识培训', owner_dept_id: 'dept-b', owner_dept_name: '技术部', description: '公司制度、企业文化与办公系统入门', suitable_members: '新入职员工', category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) },
|
||||
{ id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) },
|
||||
{ id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) },
|
||||
{ id: 'lib-1', code: 'CRS-0001', name: '新员工入职通识培训', owner_dept_id: 'dept-b', owner_dept_name: '技术部', description: '公司制度、企业文化与办公系统入门', suitable_members: '新入职员工', category: '企业文化与制度类', type: 'required', mode: 'online', lecturer_id: 'u-m1', hours: 2, material_name: '入职通识手册.pptx', file_name: '入职通识手册.pptx', file_size: 839680, knowledge_id: 'kb-lib1', question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-3, 1), updated_at: month(0, 2) },
|
||||
{ id: 'lib-2', code: 'CRS-0002', name: '冲压设备安全操作实操', owner_dept_id: 'dept-a', owner_dept_name: '冲压车间', description: '冲压机安全操作与应急处置实操训练', suitable_members: '冲压操作员', category: '安全与健康类', type: 'required', mode: 'offline', lecturer_id: 'u-m2', hours: 4, material_name: '安全操作规程.docx、实操考核表.xlsx', file_name: '安全操作规程.docx', file_size: 512000, question_bank_count: 1, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-2, 5), updated_at: month(-1, 8) },
|
||||
{ id: 'lib-3', code: 'CRS-0003', name: 'TS16949 质量体系知识', owner_dept_id: '', owner_dept_name: '', description: 'IATF 16949 体系条款与内审要点', suitable_members: '品质岗', category: '专业技能类', type: 'elective', mode: 'online', lecturer_id: '', lecturer_external: '王顾问', hours: 3, material_name: '', file_name: '', file_size: 0, question_bank_count: 0, verify_status: 'confirmed', publish_status: 'draft', lecturer_name: '', created_at: month(-1, 12), updated_at: month(-1, 12) },
|
||||
]
|
||||
|
||||
// 课程管理 · 试题管理(000153):题库与题目演示数据(编号 QB-####)
|
||||
@@ -313,6 +313,26 @@ export function resolveTrainingMock(method: string, url: string): { status: numb
|
||||
if (url.includes('/question-banks/') && url.includes('/questions')) {
|
||||
return ok({ id: `q-new-${Date.now()}`, seq_no: 0 })
|
||||
}
|
||||
// 课件管理抽屉:上传/知识库挂接/移除回显对应课程条目并模拟文件字段变更
|
||||
if (url.includes('/course-library/') && url.includes('/material/remove')) {
|
||||
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
|
||||
if (course) {
|
||||
course.file_name = ''
|
||||
course.file_size = 0
|
||||
course.knowledge_id = ''
|
||||
course.verify_status = 'pending'
|
||||
}
|
||||
return ok(course || { id: `c-new-${Date.now()}` })
|
||||
}
|
||||
if (url.includes('/course-library/') && url.includes('/material')) {
|
||||
const course = COURSE_LIBRARY_MOCK.find((c) => url.includes(`/course-library/${c.id}/`))
|
||||
if (course) {
|
||||
course.file_name = '预览课件.pdf'
|
||||
course.file_size = 1024 * 820
|
||||
course.verify_status = 'pending'
|
||||
}
|
||||
return ok(course || { id: `c-new-${Date.now()}` })
|
||||
}
|
||||
if (url.includes('/course-library/') && url.includes('/question-banks/import')) {
|
||||
return ok({ id: `b-new-${Date.now()}`, code: `QB-${String(QUESTION_BANKS_MOCK.length + 1).padStart(4, '0')}`, name: '新导入题库', question_count: 5 })
|
||||
}
|
||||
|
||||
@@ -3021,8 +3021,11 @@ const removeStarterSuggestion = (index: number) => {
|
||||
formData.value.config.question_suggestions.starters.items.splice(index, 1);
|
||||
};
|
||||
|
||||
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
|
||||
// 仅在字段为空时补值,绝不覆盖用户已选;编辑态补默认可修复存量空模型智能体,
|
||||
// 免去「模型必填」手动配置(与后端 create 兜底同规则)。
|
||||
const applyDefaultModelsIfEmpty = () => {
|
||||
if (props.mode !== 'create' || !formData.value) return
|
||||
if (!formData.value) return
|
||||
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
||||
const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
|
||||
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.
|
||||
fillBuiltinAgentDefaults();
|
||||
void loadAgentIntegrationCounts(agentData.id);
|
||||
// 编辑态同样补默认模型(仅空字段):存量空模型智能体不再被「模型必填」卡住
|
||||
applyDefaultModelsIfEmpty()
|
||||
} else {
|
||||
// 创建新智能体,使用系统默认值
|
||||
storedToolNames.value = [];
|
||||
|
||||
@@ -97,8 +97,8 @@
|
||||
|
||||
<!-- Logo - Top Left -->
|
||||
<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__text">AIDO</span>
|
||||
<span class="aido-logo" aria-label="和信智汇学院">
|
||||
<span class="aido-logo__text">和信智汇学院</span>
|
||||
<span class="aido-logo__dot"></span>
|
||||
</span>
|
||||
</a>
|
||||
@@ -611,7 +611,7 @@ const persistLoginResponse = async (response: any, skipRedirect = false) => {
|
||||
await authStore.refreshFromAuthMe()
|
||||
await nextTick()
|
||||
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`
|
||||
@@ -694,7 +694,7 @@ const acceptAndEnter = async (token: string) => {
|
||||
} finally {
|
||||
loading.value = false
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +852,7 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
if (authStore.isLoggedIn) {
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -313,6 +313,8 @@ import {
|
||||
type ScheduleKind,
|
||||
} from '@/utils/automationSchedule'
|
||||
import ModelSelector from '@/components/ModelSelector.vue'
|
||||
import { selectInitialModelId } from '@/utils/modelDefaults'
|
||||
import { useChatResourcesStore } from '@/stores/chatResources'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -323,6 +325,7 @@ const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Au
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const uiStore = useUIStore()
|
||||
const chatResources = useChatResourcesStore()
|
||||
|
||||
type Section = 'basic' | 'schedule' | 'execution' | 'notify'
|
||||
|
||||
@@ -409,6 +412,16 @@ watch(() => props.visible, (open) => {
|
||||
Object.assign(schedule, defaultScheduleForm())
|
||||
timezone.value = browserTimezone()
|
||||
maxMinutes.value = 30
|
||||
if (!a) {
|
||||
// 开箱即用:create 模式预填系统默认对话模型(与知识库/智能体编辑器
|
||||
// 的 applyDefaultModelsIfEmpty 同模式)。模型列表异步加载,回来后仅当
|
||||
// 仍为空时落值,不覆盖用户已选;编辑已有自动化时不做预填。
|
||||
void chatResources.ensureModels().then(() => {
|
||||
if (!props.automation && props.visible && !form.model_id) {
|
||||
form.model_id = selectInitialModelId(chatResources.allModels || [], 'KnowledgeQA') || ''
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
if (a) {
|
||||
Object.assign(form, {
|
||||
name: a.name,
|
||||
|
||||
@@ -889,8 +889,11 @@ const kbCreateNeedsEmbedding = computed(() => {
|
||||
return Boolean(s?.vectorEnabled || s?.keywordEnabled)
|
||||
})
|
||||
|
||||
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
|
||||
// 仅在字段为空时补值,不覆盖用户已选;与后端 CreateKnowledgeBase 的默认兜底
|
||||
// 同规则,编辑态补默认可修复存量未绑模型的知识库。
|
||||
const applyDefaultModelsIfEmpty = () => {
|
||||
if (!formData.value || editorMode.value !== 'create') return
|
||||
if (!formData.value) return
|
||||
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
||||
const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding')
|
||||
if (!formData.value.modelConfig.llmModelId && chatModelId) {
|
||||
@@ -1936,6 +1939,8 @@ watch(() => props.visible, async (newVal) => {
|
||||
// 根据模式加载数据
|
||||
if (props.mode === 'edit' && targetKbId) {
|
||||
await loadKBData(targetKbId, generation)
|
||||
// 编辑态同样补默认模型(仅空字段):存量未绑模型的知识库不再要求手动选择
|
||||
applyDefaultModelsIfEmpty()
|
||||
} else {
|
||||
// 创建模式:初始化空表单,并预填空间默认存储引擎
|
||||
formData.value = initFormData(props.initialType || 'document')
|
||||
|
||||
@@ -34,7 +34,32 @@
|
||||
<div class="panel-box org-layout__employees">
|
||||
<div class="panel-box__header">
|
||||
<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 theme="primary" @click="importVisible = true">批量导入</t-button>
|
||||
</div>
|
||||
@@ -46,6 +71,12 @@
|
||||
</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 #status="{ row }">
|
||||
<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>
|
||||
@@ -54,6 +85,8 @@
|
||||
<template #op="{ row }">
|
||||
<div class="op-group">
|
||||
<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>
|
||||
</template>
|
||||
</t-table>
|
||||
@@ -101,7 +134,7 @@
|
||||
v-for="u in platformUsers"
|
||||
:key="u.id"
|
||||
:value="u.id"
|
||||
:label="`${u.username}(${u.display_name?.trim() || u.email})${u.in_roster ? ' · 已在名册' : ''}`"
|
||||
:label="`${u.username}(${u.display_name?.trim() || u.email})${u.dept_name?.trim() ? ' · ' + u.dept_name.trim() : ''}${u.in_roster ? ' · 已在名册' : ''}`"
|
||||
:disabled="u.in_roster"
|
||||
/>
|
||||
</t-select>
|
||||
@@ -115,7 +148,7 @@
|
||||
<t-input v-model="pickerPost" placeholder="如 设备技师" />
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<div class="form-hint">工号无需填写,添加时自动取平台账号(下拉里展示的编号)。</div>
|
||||
<div class="form-hint">工号无需填写,添加时自动取平台账号;已同步部门的用户会自动带出部门,可手动调整。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="saving" :disabled="!pickerUserIds.length || !pickerDeptId" @click="onPickImport">添加到名册</t-button>
|
||||
</template>
|
||||
@@ -150,33 +183,155 @@
|
||||
<t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button>
|
||||
</template>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
adoptHomeTenant,
|
||||
applyOrgWecomSync,
|
||||
deleteDept,
|
||||
importEmployees,
|
||||
listAdoptableUsers,
|
||||
listDepts,
|
||||
listEmployees,
|
||||
listPlatformUsers,
|
||||
ORG_MODULE_TRAINING,
|
||||
previewOrgWecomSync,
|
||||
saveDept,
|
||||
updateEmployee,
|
||||
updateOrgEmployeeRoles,
|
||||
updateOrgEmployeeWecomUserid,
|
||||
type OrgAdoptableUser,
|
||||
type OrgDept,
|
||||
type OrgEmployee,
|
||||
type OrgPlatformUser,
|
||||
} 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'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const depts = ref<OrgDept[]>([])
|
||||
const employees = ref<OrgEmployee[]>([])
|
||||
const platformUsers = ref<OrgPlatformUser[]>([])
|
||||
|
||||
// 员工查找(需求:按名称/工号/部门);keyword 走后端 ListEmployees 的过滤。
|
||||
const keyword = ref('')
|
||||
|
||||
const deptFormVisible = ref(false)
|
||||
const importVisible = ref(false)
|
||||
// id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。
|
||||
@@ -193,6 +348,174 @@ const pickerPost = ref('')
|
||||
const employeeFormVisible = ref(false)
|
||||
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 = [
|
||||
{ colKey: 'name', title: '部门名称' },
|
||||
{ colKey: 'code', title: '编码', width: 140 },
|
||||
@@ -200,15 +523,18 @@ const deptColumns = [
|
||||
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
||||
]
|
||||
|
||||
const employeeColumns = [
|
||||
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
|
||||
const employeeColumns = computed(() => [
|
||||
{ colKey: 'employee_no', title: '工号', width: 90 },
|
||||
{ colKey: 'user_name', title: '姓名' },
|
||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
||||
{ colKey: 'post', title: '岗位', width: 140 },
|
||||
{ colKey: 'status', title: '状态', width: 76 },
|
||||
// 列总宽超出面板宽度时固定在右侧,避免"修改"按钮被横向滚动挤出可视区
|
||||
{ colKey: 'op', title: '操作', width: 84, fixed: 'right' },
|
||||
]
|
||||
{ colKey: 'user_name', title: '姓名', width: 110 },
|
||||
{ colKey: 'dept_name', title: '部门', width: 100 },
|
||||
{ colKey: 'post', title: '岗位', width: 120 },
|
||||
{ colKey: 'wecom_userid', title: '企微账号', width: 110 },
|
||||
{ colKey: 'roles', title: '职称角色' },
|
||||
{ colKey: 'status', title: '状态', width: 70 },
|
||||
// 列总宽超出面板宽度时固定在右侧,避免操作按钮被横向滚动挤出可视区
|
||||
{ colKey: 'op', title: '操作', width: canManage.value ? 200 : 84, fixed: 'right' },
|
||||
])
|
||||
|
||||
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
||||
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。
|
||||
@@ -219,23 +545,83 @@ const userNameMap = computed(() => {
|
||||
})
|
||||
const employeeName = (row: OrgEmployee) => row.user_name || userNameMap.value[row.user_id] || ''
|
||||
|
||||
const loadAll = async () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
// 从平台用户添加:部门自动带出(000156)
|
||||
// Casdoor 同步把部门编号/名称落在平台账号上(users.dept_code/dept_name);
|
||||
// 选中用户后,若所选用户都带同一个部门编号且能映射到左侧组织架构部门,
|
||||
// 则自动预选该部门——仍可手动改,与导入接口的部门必填校验解耦。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// 部门编号 → 组织架构部门 id(列表顺序在后,同编号后写入者胜出,与唯一索引兜底一致)。
|
||||
const deptIdByCode = computed(() => {
|
||||
const m: Record<string, string> = {}
|
||||
for (const d of depts.value) {
|
||||
const code = d.code?.trim()
|
||||
if (code) m[code] = d.id
|
||||
}
|
||||
return m
|
||||
})
|
||||
|
||||
watch(pickerUserIds, (ids) => {
|
||||
if (!ids.length) return
|
||||
const selected = platformUsers.value.filter((u) => ids.includes(u.id))
|
||||
if (!selected.length) return
|
||||
const codes = selected.map((u) => u.dept_code?.trim() || '')
|
||||
// 有任一用户没同步到部门,或部门编号不一致 → 不自动带出,保留当前选择。
|
||||
if (codes.some((c) => !c)) return
|
||||
const code = codes[0]
|
||||
if (codes.some((c) => c !== code)) return
|
||||
const deptId = deptIdByCode.value[code]
|
||||
if (deptId) pickerDeptId.value = deptId
|
||||
})
|
||||
|
||||
// 员工列表:module_key='training' 联查职称角色展示;keyword 按姓名/工号/部门过滤。
|
||||
const loadEmployees = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
||||
const [d, e, u] = await Promise.all([
|
||||
listDepts(),
|
||||
listEmployees({ page_size: 500 }),
|
||||
listPlatformUsers().catch(() => null),
|
||||
])
|
||||
depts.value = unwrap(d) || []
|
||||
const e = await listEmployees({
|
||||
module_key: ORG_MODULE_TRAINING,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
page_size: 500,
|
||||
})
|
||||
employees.value = unwrap(e)?.items || []
|
||||
platformUsers.value = unwrap(u) || []
|
||||
} finally {
|
||||
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 = () => {
|
||||
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
|
||||
deptFormVisible.value = true
|
||||
@@ -319,7 +705,7 @@ const onPickImport = async () => {
|
||||
pickerVisible.value = false
|
||||
pickerUserIds.value = []
|
||||
pickerDeptId.value = ''
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('添加失败')
|
||||
} finally {
|
||||
@@ -355,7 +741,7 @@ const onSaveEmployee = async () => {
|
||||
})
|
||||
MessagePlugin.success('员工档案已更新')
|
||||
employeeFormVisible.value = false
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('保存失败')
|
||||
} finally {
|
||||
@@ -400,7 +786,7 @@ const onImport = async () => {
|
||||
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
|
||||
importVisible.value = false
|
||||
importText.value = ''
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
|
||||
} finally {
|
||||
@@ -408,7 +794,13 @@ const onImport = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadAll)
|
||||
onMounted(() => {
|
||||
loadAll()
|
||||
loadProfile()
|
||||
fetchRoleDict().then((d) => {
|
||||
roleDict.value = d
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -468,4 +860,55 @@ onMounted(loadAll)
|
||||
word-break: break-all;
|
||||
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>
|
||||
@@ -36,6 +36,20 @@
|
||||
</t-popup>
|
||||
</div>
|
||||
<div class="members-header-actions">
|
||||
<!-- Excel 花名册批量导入:面向"手上已有员工名单"的批量加人场景,
|
||||
与右侧单个邀请 / 共享链接两种方式并列。 -->
|
||||
<t-button v-if="canManage" variant="text" size="small" class="header-audit-btn member-import-btn"
|
||||
@click="openImportDialog">
|
||||
<template #icon><t-icon name="upload" /></template>
|
||||
{{ $t('tenantMember.import.button') }}
|
||||
</t-button>
|
||||
<!-- CASDOOR 用户目录同步(000156):管理 API 拉全量用户自动开户/入空间,
|
||||
部门编号/名称对齐组织架构;单向增量,不删不停不改角色。 -->
|
||||
<t-button v-if="canManage" variant="text" size="small" class="header-audit-btn member-import-btn"
|
||||
:loading="syncCasdoorLoading" @click="openSyncCasdoorDialog">
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ $t('tenantMember.syncCasdoor.button') }}
|
||||
</t-button>
|
||||
<t-button v-if="canViewAudit" variant="text" size="small" class="header-audit-btn" @click="openAuditDrawer">
|
||||
<template #icon><t-icon name="history" /></template>
|
||||
{{ $t('tenantMember.audit.tabLabel') }}
|
||||
@@ -316,6 +330,9 @@
|
||||
<span v-if="memberSecondary(row)" class="member-email">{{ memberSecondary(row) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #deptName="{ row }">
|
||||
<span class="member-dept-name">{{ row.dept_name?.trim() || '—' }}</span>
|
||||
</template>
|
||||
<template #displayName="{ row }">
|
||||
<span>{{ row.display_name?.trim() || '—' }}</span>
|
||||
</template>
|
||||
@@ -499,6 +516,142 @@
|
||||
</div>
|
||||
</div>
|
||||
</SettingDrawer>
|
||||
|
||||
<!-- Excel 批量导入弹窗:select 步(下载模板 + 选文件)→ result 步(汇总 + 失败明细)。
|
||||
上传中禁止误关;关闭即重置,下次打开回到选择文件步。 -->
|
||||
<t-dialog v-model:visible="importDialogVisible" class="member-import-dialog"
|
||||
:header="importStep === 'select' ? $t('tenantMember.import.dialogTitle') : $t('tenantMember.import.resultTitle')"
|
||||
width="620px" :footer="false" :close-btn="!importUploading" :close-on-overlay-click="!importUploading">
|
||||
<template v-if="importStep === 'select'">
|
||||
<p class="member-import-desc">{{ $t('tenantMember.import.description') }}</p>
|
||||
<t-alert v-if="importError" theme="error" :message="importError" class="member-import-error" />
|
||||
<div class="member-import-file" :class="{ 'member-import-file--picked': importFile }" role="button"
|
||||
tabindex="0" @click="triggerImportFileSelect" @keydown.enter.prevent="triggerImportFileSelect">
|
||||
<t-icon name="file-excel" class="member-import-file-icon" />
|
||||
<div class="member-import-file-text">
|
||||
<span class="member-import-file-name">
|
||||
{{ importFile ? importFile.name : $t('tenantMember.import.pickFile') }}
|
||||
</span>
|
||||
<span v-if="importFile" class="member-import-file-hint">{{ $t('tenantMember.import.repick') }}</span>
|
||||
<span v-else class="member-import-file-hint">{{ $t('tenantMember.import.fileHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<input ref="importFileInputRef" type="file" accept=".xlsx,.xls" style="display: none"
|
||||
@change="onImportFileChange" />
|
||||
<div class="member-import-footer">
|
||||
<t-button variant="outline" :disabled="importUploading" @click="downloadImportTemplate">
|
||||
<template #icon><t-icon name="download" /></template>
|
||||
{{ $t('tenantMember.import.downloadTemplate') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" :loading="importUploading" :disabled="!importFile" @click="submitImport">
|
||||
{{ $t('tenantMember.import.submit') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="member-import-summary">
|
||||
<div class="member-import-summary-item member-import-summary-item--added">
|
||||
<span class="member-import-summary-num">{{ importResult?.added ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.import.summaryAdded') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--created">
|
||||
<span class="member-import-summary-num">{{ importResult?.created_accounts ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.import.summaryCreated') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--exists">
|
||||
<span class="member-import-summary-num">{{ importResult?.already_member ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.import.summaryExists') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--failed">
|
||||
<span class="member-import-summary-num">{{ importResult?.failed ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.import.summaryFailed') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="importFailedRows.length > 0">
|
||||
<p class="member-import-failed-title">{{ $t('tenantMember.import.failedListTitle') }}</p>
|
||||
<div class="member-import-failed-table narrow-scrollbar">
|
||||
<div v-for="row in importFailedRows" :key="row.row" class="member-import-failed-row">
|
||||
<span class="member-import-failed-no">{{ $t('tenantMember.import.rowLabel', { row: row.row }) }}</span>
|
||||
<span class="member-import-failed-who">{{ row.employee_no || row.email || row.name || '—' }}</span>
|
||||
<span class="member-import-failed-reason">{{ row.reason }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="member-import-footer">
|
||||
<t-button v-if="importFailedRows.length > 0" variant="outline" @click="resetImportToSelect">
|
||||
{{ $t('tenantMember.import.reimport') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" @click="importDialogVisible = false">
|
||||
{{ $t('common.close') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- CASDOOR 同步弹窗(000156):confirm 步(说明 + 确认)→ result 步(汇总 + 跳过明细)。
|
||||
同步中禁止误关;关闭即重置,下次打开回到确认步。 -->
|
||||
<t-dialog v-model:visible="syncCasdoorDialogVisible" class="member-import-dialog"
|
||||
:header="syncCasdoorStep === 'confirm' ? $t('tenantMember.syncCasdoor.dialogTitle') : $t('tenantMember.syncCasdoor.resultTitle')"
|
||||
width="620px" :footer="false" :close-btn="!syncCasdoorLoading"
|
||||
:close-on-overlay-click="!syncCasdoorLoading">
|
||||
<template v-if="syncCasdoorStep === 'confirm'">
|
||||
<p class="member-import-desc">{{ $t('tenantMember.syncCasdoor.description') }}</p>
|
||||
<t-alert v-if="syncCasdoorError" theme="error" :message="syncCasdoorError" class="member-import-error" />
|
||||
<div class="member-import-footer">
|
||||
<t-button variant="outline" :disabled="syncCasdoorLoading" @click="syncCasdoorDialogVisible = false">
|
||||
{{ $t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" :loading="syncCasdoorLoading" @click="submitSyncCasdoor">
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ $t('tenantMember.syncCasdoor.confirm') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="member-import-summary">
|
||||
<div class="member-import-summary-item member-import-summary-item--total">
|
||||
<span class="member-import-summary-num">{{ syncCasdoorResult?.casdoor_total ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.syncCasdoor.summaryTotal') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--created">
|
||||
<span class="member-import-summary-num">{{ syncCasdoorResult?.users_created ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.syncCasdoor.summaryCreated') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--added">
|
||||
<span class="member-import-summary-num">{{ syncCasdoorResult?.members_added ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.syncCasdoor.summaryAdded') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--exists">
|
||||
<span class="member-import-summary-num">{{ syncCasdoorResult?.members_existing ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.syncCasdoor.summaryExists') }}</span>
|
||||
</div>
|
||||
<div class="member-import-summary-item member-import-summary-item--depts">
|
||||
<span class="member-import-summary-num">{{ syncCasdoorResult?.depts_created ?? 0 }}</span>
|
||||
<span class="member-import-summary-label">{{ $t('tenantMember.syncCasdoor.summaryDepts') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<t-alert v-if="syncCasdoorResult && !syncCasdoorResult.dept_source" theme="warning"
|
||||
:message="$t('tenantMember.syncCasdoor.noDeptHint')" class="member-import-error" />
|
||||
<p v-else-if="syncCasdoorResult?.dept_source" class="member-import-desc member-sync-dept-source">
|
||||
{{ $t('tenantMember.syncCasdoor.deptSourceHint', { field: syncCasdoorResult.dept_source }) }}
|
||||
</p>
|
||||
<template v-if="syncCasdoorSkipped.length > 0">
|
||||
<p class="member-import-failed-title">{{ $t('tenantMember.syncCasdoor.skippedListTitle') }}</p>
|
||||
<div class="member-import-failed-table narrow-scrollbar">
|
||||
<div v-for="(row, idx) in syncCasdoorSkipped" :key="idx" class="member-import-failed-row">
|
||||
<span class="member-import-failed-no">{{ row.name || '—' }}</span>
|
||||
<span class="member-import-failed-who">{{ row.email || '—' }}</span>
|
||||
<span class="member-import-failed-reason">{{ row.reason }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="member-import-footer">
|
||||
<t-button theme="primary" @click="syncCasdoorDialogVisible = false">
|
||||
{{ $t('common.close') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -506,6 +659,7 @@
|
||||
import { computed, nextTick, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import * as XLSX from 'xlsx'
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import { copyWithToast } from '@/utils/clipboard'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
@@ -515,8 +669,12 @@ import {
|
||||
listMembers,
|
||||
updateMemberRole,
|
||||
removeMember,
|
||||
importMembers,
|
||||
syncCasdoorMembers,
|
||||
type TenantMember,
|
||||
type TenantRole,
|
||||
type MemberImportResult,
|
||||
type CasdoorSyncResult,
|
||||
} from '@/api/tenant/members'
|
||||
import {
|
||||
listTenantInvitations,
|
||||
@@ -729,6 +887,7 @@ function roleMatrixIcon(role: TenantRole): string {
|
||||
|
||||
const columns = computed(() => [
|
||||
{ colKey: 'member', title: t('tenantMember.columns.member'), ellipsis: true, minWidth: 230 },
|
||||
{ colKey: 'deptName', title: t('tenantMember.columns.deptName'), ellipsis: true, width: 130 },
|
||||
{ colKey: 'displayName', title: t('tenantMember.columns.displayName'), width: 120 },
|
||||
{ colKey: 'role', title: t('tenantMember.columns.role'), width: 168 },
|
||||
{ colKey: 'joined_at', title: t('tenantMember.columns.joinedAt'), width: 154 },
|
||||
@@ -845,6 +1004,134 @@ function onMembersPageChange() {
|
||||
void loadMembers()
|
||||
}
|
||||
|
||||
// ---- Excel 批量导入 --------------------------------------------------------
|
||||
// 面向"手上已有 HR 花名册"的批量加人:模板下载(SheetJS 前端生成)→
|
||||
// 选文件上传 → 后端逐行解析(按邮箱/工号匹配已有账号,未注册自动开户)
|
||||
// → 展示汇总与失败明细。与邀请/共享链接两个 popup 并列的第三种加人方式。
|
||||
|
||||
const importDialogVisible = ref(false)
|
||||
/** 'select':模板下载与选文件;'result':导入结果汇总 */
|
||||
const importStep = ref<'select' | 'result'>('select')
|
||||
const importFile = ref<File | null>(null)
|
||||
const importFileInputRef = ref<HTMLInputElement | null>(null)
|
||||
const importUploading = ref(false)
|
||||
const importError = ref('')
|
||||
const importResult = ref<MemberImportResult['data'] | null>(null)
|
||||
|
||||
/** 失败行明细(行号 + 工号/邮箱 + 后端原因),汇总区已给数量故只列失败行 */
|
||||
const importFailedRows = computed(
|
||||
() => importResult.value?.results.filter((r) => r.status === 'failed') ?? [],
|
||||
)
|
||||
|
||||
function openImportDialog() {
|
||||
resetImportToSelect()
|
||||
importDialogVisible.value = true
|
||||
}
|
||||
|
||||
function resetImportToSelect() {
|
||||
importStep.value = 'select'
|
||||
importFile.value = null
|
||||
importError.value = ''
|
||||
importResult.value = null
|
||||
}
|
||||
|
||||
function triggerImportFileSelect() {
|
||||
importFileInputRef.value?.click()
|
||||
}
|
||||
|
||||
function onImportFileChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement
|
||||
const file = input.files?.[0] ?? null
|
||||
// 清空 value 让重复选择同一文件也能触发 change。
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
const lower = file.name.toLowerCase()
|
||||
if (!lower.endsWith('.xlsx') && !lower.endsWith('.xls')) {
|
||||
importError.value = t('tenantMember.import.invalidFileType')
|
||||
importFile.value = null
|
||||
return
|
||||
}
|
||||
importError.value = ''
|
||||
importFile.value = file
|
||||
}
|
||||
|
||||
/** 前端生成导入模板(表头 + 两行示例,覆盖"有邮箱/部门"与"留空走占位邮箱、
|
||||
* 部门自动匹配"两种写法),与知识库 FAQ 模板下载同模式(XLSX.writeFile)。
|
||||
* 部门列填写部门管理中已维护的部门名称,后端按名称/编号自动匹配,未命中留空。 */
|
||||
function downloadImportTemplate() {
|
||||
const rows = [
|
||||
{ 工号: '26080007', 姓名: '张三', 部门: '研发部', 邮箱: '26080007@example.com', 角色: '访客' },
|
||||
{ 工号: '26080008', 姓名: '李四', 部门: '', 邮箱: '', 角色: '编辑' },
|
||||
]
|
||||
const ws = XLSX.utils.json_to_sheet(rows, { header: ['工号', '姓名', '部门', '邮箱', '角色'] })
|
||||
ws['!cols'] = [{ wch: 16 }, { wch: 12 }, { wch: 16 }, { wch: 30 }, { wch: 12 }]
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, '成员导入')
|
||||
XLSX.writeFile(wb, '成员导入模板.xlsx')
|
||||
}
|
||||
|
||||
async function submitImport() {
|
||||
if (!importFile.value || importUploading.value || !activeTenantId.value) return
|
||||
importUploading.value = true
|
||||
importError.value = ''
|
||||
try {
|
||||
const resp = await importMembers(activeTenantId.value, importFile.value)
|
||||
if (!resp.success || !resp.data) {
|
||||
importError.value = resp.message || t('tenantMember.errors.generic')
|
||||
return
|
||||
}
|
||||
importResult.value = resp.data
|
||||
importStep.value = 'result'
|
||||
// 新成员/新建账号已直接进空间,刷新成员列表(含总数徽标)。
|
||||
await loadMembers()
|
||||
} catch (err: any) {
|
||||
importError.value = err?.message || t('tenantMember.errors.generic')
|
||||
} finally {
|
||||
importUploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---- CASDOOR 同步(000156)-----------------------------------------------
|
||||
// 与批量导入同模式的确认→结果两步弹窗。同步为单向增量幂等:
|
||||
// 不删除、不停用、不改已有成员角色;部门编号/名称对齐组织架构。
|
||||
|
||||
const syncCasdoorDialogVisible = ref(false)
|
||||
const syncCasdoorStep = ref<'confirm' | 'result'>('confirm')
|
||||
const syncCasdoorLoading = ref(false)
|
||||
const syncCasdoorError = ref('')
|
||||
const syncCasdoorResult = ref<CasdoorSyncResult | null>(null)
|
||||
|
||||
/** 跳过明细列表(result 步展示;空数组时显示"无跳过"提示不需要,直接隐藏块) */
|
||||
const syncCasdoorSkipped = computed(() => syncCasdoorResult.value?.skipped ?? [])
|
||||
|
||||
function openSyncCasdoorDialog() {
|
||||
syncCasdoorStep.value = 'confirm'
|
||||
syncCasdoorError.value = ''
|
||||
syncCasdoorResult.value = null
|
||||
syncCasdoorDialogVisible.value = true
|
||||
}
|
||||
|
||||
async function submitSyncCasdoor() {
|
||||
if (syncCasdoorLoading.value || !activeTenantId.value) return
|
||||
syncCasdoorLoading.value = true
|
||||
syncCasdoorError.value = ''
|
||||
try {
|
||||
const resp = await syncCasdoorMembers(activeTenantId.value)
|
||||
if (!resp.success || !resp.data) {
|
||||
syncCasdoorError.value = resp.message || t('tenantMember.syncCasdoor.failed')
|
||||
return
|
||||
}
|
||||
syncCasdoorResult.value = resp.data
|
||||
syncCasdoorStep.value = 'result'
|
||||
// 新成员/新账号已直接进空间,刷新成员列表(含总数徽标与部门列)。
|
||||
await loadMembers()
|
||||
} catch (err: any) {
|
||||
syncCasdoorError.value = err?.message || t('tenantMember.syncCasdoor.failed')
|
||||
} finally {
|
||||
syncCasdoorLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(searchQuery, () => {
|
||||
if (!activeTenantId.value) return
|
||||
window.clearTimeout(memberSearchDebounceTimer)
|
||||
@@ -1497,6 +1784,15 @@ watch(
|
||||
}
|
||||
}
|
||||
|
||||
/* 所属部门列(000156 Casdoor 同步态):无部门显示占位符,弱化为次要文字。 */
|
||||
.member-dept-name {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
.settings-section-header();
|
||||
flex-shrink: 0;
|
||||
@@ -2448,4 +2744,174 @@ watch(
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* 成员 Excel 批量导入弹窗:t-dialog teleport 到 body,须全局样式。
|
||||
* 语义与邀请/共享链接 popup 保持一致的间距与圆角卡片观感。 */
|
||||
.member-import-dialog .member-import-desc {
|
||||
margin: 0 0 12px;
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1.6;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-error {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 18px 16px;
|
||||
border: 1px dashed var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md, 8px);
|
||||
background: var(--td-bg-color-secondarycontainer, var(--td-bg-color-container));
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s ease, background-color 0.2s ease;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file:hover,
|
||||
.member-import-dialog .member-import-file:focus-visible {
|
||||
border-color: var(--td-brand-color);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file--picked {
|
||||
border-style: solid;
|
||||
border-color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file-icon {
|
||||
font-size: 28px;
|
||||
color: var(--td-success-color, var(--td-brand-color));
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file-name {
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-file-hint {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin: 4px 0 4px;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 12px 8px;
|
||||
border-radius: var(--app-radius-sm, 6px);
|
||||
background: var(--td-bg-color-secondarycontainer, var(--td-bg-color-container));
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-num {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-label {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-item--created .member-import-summary-num {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-item--failed .member-import-summary-num {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
/* CASDOOR 同步结果卡的两种新配色:目录总数(中性)与新建部门(成功绿)。 */
|
||||
.member-import-dialog .member-import-summary-item--total .member-import-summary-num {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-summary-item--depts .member-import-summary-num {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-sync-dept-source {
|
||||
margin: 10px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-title {
|
||||
margin: 12px 0 8px;
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-table {
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-sm, 6px);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
padding: 8px 12px;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-row + .member-import-failed-row {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-no {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
min-width: 44px;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-who {
|
||||
flex-shrink: 0;
|
||||
max-width: 160px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--td-text-color-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.member-import-dialog .member-import-failed-reason {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
color: var(--td-error-color);
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@@ -1,19 +1,21 @@
|
||||
<template>
|
||||
<!-- 学员扫码签到落地页:培训签到页二维码 → 企微/相机扫码直达,自动定位并提交签到 -->
|
||||
<!-- 学员扫码签到落地页(2026-11 企微扫码免登需求):
|
||||
企微「扫一扫」→ 静默免登(自动登录)→ 课程信息 + 签到倒计时 → 点击签到
|
||||
→ 成功后自动进入该课程详情页。非企微环境提示改用企微扫码。 -->
|
||||
<div class="checkin-page">
|
||||
<div class="checkin-card">
|
||||
<div class="checkin-card__icon" :class="`is-${state}`">
|
||||
<!-- 定位中/提交中 -->
|
||||
<svg v-if="state === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<div class="checkin-card__icon" :class="`is-${iconState}`">
|
||||
<!-- 免登中/取位中 -->
|
||||
<svg v-if="iconState === 'pending'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="3.2" />
|
||||
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
|
||||
</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" />
|
||||
<path d="m8.5 12.2 2.4 2.4 4.8-4.9" />
|
||||
</svg>
|
||||
<!-- 失败 -->
|
||||
<!-- 失败/受阻 -->
|
||||
<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" />
|
||||
<path d="M12 7.5V13" />
|
||||
@@ -28,42 +30,271 @@
|
||||
{{ record.status === 'normal' ? '签到成功' : record.status === 'late' ? '迟到签到' : '已提交,待复核' }}
|
||||
</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">
|
||||
<t-button v-if="state === 'error'" theme="primary" @click="submit">重新签到</t-button>
|
||||
<t-button variant="outline" @click="goTraining">前往企业培训</t-button>
|
||||
<t-button v-if="state === 'error' && retryable" theme="primary" @click="sign">重新签到</t-button>
|
||||
<t-button v-if="state !== 'submitting'" variant="outline" @click="goTraining">前往企业培训</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
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'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
type CheckinState = 'pending' | 'success' | 'error'
|
||||
const state = ref<CheckinState>('pending')
|
||||
type CheckinState = 'boot' | 'authing' | 'ready' | 'submitting' | 'success' | 'error' | 'blocked'
|
||||
const state = ref<CheckinState>('boot')
|
||||
const page = ref<WecomCheckinPageData | null>(null)
|
||||
const record = ref<TrainingSignRecord | null>(null)
|
||||
const errorMsg = ref('')
|
||||
// 定位坐标:拒绝授权/不可用时以 0,0 提交,由后端 sign_policy(强制定位)决定是否放行
|
||||
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(() => {
|
||||
if (state.value === 'pending') return '正在签到…'
|
||||
if (state.value === 'success') return '签到完成'
|
||||
return '签到失败'
|
||||
switch (state.value) {
|
||||
case 'boot':
|
||||
case 'authing':
|
||||
return '正在进入签到…'
|
||||
case 'ready':
|
||||
return page.value?.already_signed ? '您已签到' : '培训签到'
|
||||
case 'submitting':
|
||||
return '正在签到…'
|
||||
case 'success':
|
||||
return '签到完成'
|
||||
default:
|
||||
return state.value === 'blocked' ? '无法签到' : '签到失败'
|
||||
}
|
||||
})
|
||||
|
||||
const hint = computed(() => {
|
||||
if (state.value === 'pending') return '正在获取定位并提交签到,请保持页面打开'
|
||||
if (state.value === 'success') return `签到时间:${fmtBeijingTime(record.value?.signed_at || null) || '—'}`
|
||||
return errorMsg.value || '签到码无效或已过期,请联系讲师刷新签到码'
|
||||
switch (state.value) {
|
||||
case 'boot':
|
||||
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 秒,失败不阻塞签到(是否强制定位由后端规则决定)
|
||||
const locate = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
@@ -77,29 +308,41 @@ const locate = () =>
|
||||
},
|
||||
() => {
|
||||
window.clearTimeout(timer)
|
||||
MessagePlugin.warning('未获取到定位,如课程开启定位校验将无法签到')
|
||||
MessagePlugin.warning('未获取到定位,如课程开启定位校验将标记定位异常')
|
||||
resolve()
|
||||
},
|
||||
{ timeout: 5500, maximumAge: 30000 },
|
||||
)
|
||||
})
|
||||
|
||||
const submit = async () => {
|
||||
state.value = 'pending'
|
||||
const token = String(route.params.token || '')
|
||||
if (!token) {
|
||||
state.value = 'error'
|
||||
errorMsg.value = '签到链接不完整'
|
||||
return
|
||||
}
|
||||
// 点击签到(2026-11 需求:不再进页自动签):工号 + 随机时间戳随请求提交,
|
||||
// 后端做当天性/名单硬校验与防重放。
|
||||
const sign = async () => {
|
||||
if (!page.value || signDisabled.value) return
|
||||
state.value = 'submitting'
|
||||
errorMsg.value = ''
|
||||
await locate()
|
||||
const nonce = `${Date.now()}${Math.random().toString(36).slice(2, 10)}`
|
||||
try {
|
||||
const res = await checkin(token, geo.value.lat, geo.value.lng, 'wecom_scan')
|
||||
record.value = (unwrap(res) as TrainingSignRecord | undefined) || null
|
||||
const res = unwrap<TrainingSignRecord>(
|
||||
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'
|
||||
stopCountdown()
|
||||
// 签到成功 → 已自动登录,稍作停留后进入该课程详情页(需求补充 3)。
|
||||
window.setTimeout(() => {
|
||||
if (page.value?.course_id) {
|
||||
router.push(`/platform/training/course/${page.value.course_id}`)
|
||||
}
|
||||
}, 1800)
|
||||
} catch (e: any) {
|
||||
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')
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -173,6 +441,16 @@ onMounted(submit)
|
||||
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 {
|
||||
display: flex;
|
||||
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 {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.55; }
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
</t-tag>
|
||||
<h2 class="detail-name">{{ course?.name || '课程详情' }}</h2>
|
||||
<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 class="detail-meta">
|
||||
<span v-if="course">学时 {{ course.hours }}<template v-if="course.credits"> · 学分 {{ course.credits }}</template></span>
|
||||
@@ -57,14 +61,6 @@
|
||||
active
|
||||
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
|
||||
v-else-if="current"
|
||||
class="preview-empty"
|
||||
@@ -209,7 +205,6 @@ const previewKind = (m: TrainingMaterial) => {
|
||||
return 'unsupported'
|
||||
}
|
||||
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 kind = previewKind(m)
|
||||
@@ -225,28 +220,27 @@ const stopHeartbeat = () => {
|
||||
docPercentStep = 0
|
||||
}
|
||||
|
||||
// 打开课件:文档带 knowledge_id 时走知识库流(DocumentPreview 自带拉取);
|
||||
// 视频/仅 file_key 的课件统一走课件文件流(blob 播放/渲染)。
|
||||
// 打开课件:统一走培训域课件文件流(blob 播放/渲染)。不走知识库文档预览
|
||||
// 通道(/knowledge/:id/preview):该通道按调用方所在空间做知识库鉴权,000160
|
||||
// 跨空间学员(培训数据在档案空间)会被 403「Permission denied」拦截;培训域
|
||||
// 文件流按解析后的培训租户服务端取文件,与下载/和信课程抽屉同口径。
|
||||
const openMaterial = async (m: TrainingMaterial) => {
|
||||
if (current.value?.id === m.id) return
|
||||
stopHeartbeat()
|
||||
current.value = m
|
||||
docBlob.value = null
|
||||
if (!m.knowledge_id && !m.file_key) return
|
||||
if (isVideo(m) || !m.knowledge_id) {
|
||||
previewLoading.value = true
|
||||
try {
|
||||
docBlob.value = await downloadMaterialFile(m.id)
|
||||
if (isVideo(m)) bindVideoHeartbeat()
|
||||
} catch {
|
||||
MessagePlugin.error('课件文件加载失败,请稍后重试')
|
||||
current.value = null
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
return
|
||||
previewLoading.value = true
|
||||
try {
|
||||
docBlob.value = await downloadMaterialFile(m.id)
|
||||
if (isVideo(m)) bindVideoHeartbeat()
|
||||
else startDocHeartbeat(m)
|
||||
} catch {
|
||||
MessagePlugin.error('课件文件加载失败,请稍后重试')
|
||||
current.value = null
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
startDocHeartbeat(m)
|
||||
}
|
||||
|
||||
// ---- 学习进度心跳 ----
|
||||
@@ -358,6 +352,12 @@ const goBack = () => {
|
||||
else router.push('/platform/training/dashboard')
|
||||
}
|
||||
|
||||
// 培训签到:携 courseId 跳「培训签到」页,SignPanel.applyRouteCourse 自动选中
|
||||
// 该课程的进行中/最近场次(与「月培训计划-记录」跳转同一查询参数口径)。
|
||||
const goSignin = () => {
|
||||
router.push({ path: '/platform/training/sign', query: { courseId } })
|
||||
}
|
||||
|
||||
const loadAll = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -414,6 +414,12 @@ onMounted(loadAll)
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// 培训签到入口:页头行右对齐(2026-11 需求)
|
||||
.detail-signin {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.detail-name {
|
||||
margin: 0;
|
||||
font-size: var(--app-text-xl, 20px);
|
||||
|
||||
@@ -51,19 +51,15 @@
|
||||
<t-empty v-else class="training-empty" description="月培训计划仅课长/经理/人事/讲师可见,学员请前往培训中心课程目录" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'library'">
|
||||
<LibraryPanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="课程管理仅课长/经理/人事/讲师可见" />
|
||||
<!-- 课程管理全员可见(000157):数据范围与按钮权限按角色细分(人事全部/
|
||||
课长经理本部门/讲师学员仅「与我相关」),细控在 LibraryPanel 与后端 -->
|
||||
<LibraryPanel :roles="myRoles" :admin="isAdmin" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'sign'">
|
||||
<SignPanel v-if="canManageTabs" :roles="myRoles" :admin="isAdmin" />
|
||||
<t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" />
|
||||
</template>
|
||||
<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'">
|
||||
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
|
||||
<RulePanel v-if="canManageConfig" />
|
||||
@@ -85,7 +81,6 @@ import PlanPanel from './components/PlanPanel.vue'
|
||||
import CoursePanel from './components/CoursePanel.vue'
|
||||
import LibraryPanel from './components/LibraryPanel.vue'
|
||||
import SignPanel from './components/SignPanel.vue'
|
||||
import MemberPanel from './components/MemberPanel.vue'
|
||||
import StudyPanel from './components/StudyPanel.vue'
|
||||
import RulePanel from './components/RulePanel.vue'
|
||||
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
|
||||
@@ -101,7 +96,7 @@ const TRAINING_TABS_META: Record<string, { title: string; desc: string }> = {
|
||||
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
|
||||
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
|
||||
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
|
||||
members: { title: '职称角色', desc: '名册来自「组织架构」,此处维护员工职称角色' },
|
||||
// members(职称角色)已并入「组织架构」页维护,路由 /platform/training/members 重定向过去
|
||||
rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' },
|
||||
}
|
||||
|
||||
@@ -115,10 +110,12 @@ const authStore = useAuthStore()
|
||||
// 职称角色字典(配置中心可配);myRoles = 实际分配角色按「权限分配」传递展开后的
|
||||
// 权限并集 —— 各子页既有 canXxx 判断因此对自定义角色自动生效,无需逐一修改。
|
||||
const roleDict = ref<TrainingRoleDef[]>([])
|
||||
const loadRoleDict = () =>
|
||||
fetchRoleDict().then((d) => {
|
||||
roleDict.value = d
|
||||
})
|
||||
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
|
||||
fetchRoleDict().then((d) => {
|
||||
roleDict.value = d
|
||||
})
|
||||
loadRoleDict()
|
||||
|
||||
// 空间 Admin/Owner 视同培训管理角色(与后端 requireRoles 的 bypass 一致),
|
||||
// 保证冷启动时管理员即可进入职称角色/配置中心子页完成首批授权。
|
||||
@@ -212,6 +209,15 @@ const loadProfile = async () => {
|
||||
onMounted(() => {
|
||||
loadProfile()
|
||||
})
|
||||
|
||||
// 侧栏在企业培训各子页间切换时复用同一页面实例(不重挂载):本人职称角色可能刚在
|
||||
// 「职称角色」子页被分配/回收,角色权限字典可能刚在「配置中心」子页被修改。切换
|
||||
// 子页时重取这两项,否则各子页会沿用挂载时的旧 myRoles —— 例如刚给自己分配了
|
||||
// 课长,课程管理的核验/删除按钮却不出现,须整页刷新才生效。
|
||||
watch(activeTab, () => {
|
||||
loadProfile()
|
||||
loadRoleDict()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
|
||||
@@ -30,6 +30,9 @@
|
||||
<template v-if="filter === 'mine'">
|
||||
<span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span>
|
||||
<span class="catalog-stats__pending" :class="{ 'is-info': pendingStartCount > 0 }">待开始 {{ pendingStartCount }} 门</span>
|
||||
<!-- 我主讲/我参加统计(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>
|
||||
</div>
|
||||
|
||||
@@ -98,16 +101,61 @@
|
||||
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
||||
/>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import DocumentPreview from '@/components/document-preview.vue'
|
||||
import {
|
||||
downloadCourseLibraryMaterial,
|
||||
getMyProfile,
|
||||
listCourses,
|
||||
listCourseLibrary,
|
||||
listMyEnrolledCourseIds,
|
||||
listMyExamRecords,
|
||||
listMyLearningTasks,
|
||||
listSessions,
|
||||
@@ -125,9 +173,13 @@ const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
||||
const router = useRouter()
|
||||
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
|
||||
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护;
|
||||
// 和信课程卡片为课程资产展示(000154),无学习页不跳转。
|
||||
// 和信课程卡片点开即学(000160):打开课件在线预览抽屉。
|
||||
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) {
|
||||
goMaintain(card.id)
|
||||
return
|
||||
@@ -140,6 +192,52 @@ const goMaintain = (courseId: string) => {
|
||||
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 courses = ref<TrainingCourse[]>([])
|
||||
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计
|
||||
@@ -147,6 +245,8 @@ const lecturerCourses = ref<TrainingCourse[]>([])
|
||||
const myProfile = ref<TrainingMember | null>(null)
|
||||
const myTasks = ref<LearningTask[]>([])
|
||||
const sessions = ref<TrainingCourseSession[]>([])
|
||||
// 我经场次学员名单报名的课程 id 集合(「我参加」判定;失败回退空集不阻断)
|
||||
const myEnrolledCourseIds = ref<Set<string>>(new Set())
|
||||
// 课程管理资产(000154):「和信课程」目录 = 课程管理已发布且部门范围覆盖查看人的课程
|
||||
const libraryItems = ref<TrainingLibraryCourse[]>([])
|
||||
// 我的考试记录(000154):「我的考试」页签数据源
|
||||
@@ -164,13 +264,24 @@ const keyword = ref('')
|
||||
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
||||
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
||||
|
||||
// 「和信课程」(000154):课程管理中已发布、且部门范围覆盖查看人的课程
|
||||
// (所属部门为空 = 全员课程;有部门则需与我的部门一致)
|
||||
// 「和信课程」(000160):已发布 + 适合人员覆盖查看人 —— 「全部」全员可见;
|
||||
// 000159 多部门口径:值按「、」拆分(逗号/分号兼容归一)后与查看人部门名做
|
||||
// 成员匹配;未设置适合人员的存量课程沿用原部门范围口径(所属部门为空 = 全员,
|
||||
// 否则须与我的部门一致)。后端 scope=catalog 已按同口径过滤,此处保留客户端兜底。
|
||||
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
||||
const myDeptName = computed(() => (myProfile.value?.dept_name || '').trim())
|
||||
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
||||
libraryItems.value.filter(
|
||||
(c) => c.publish_status === 'published' && (!c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value),
|
||||
),
|
||||
libraryItems.value.filter((c) => {
|
||||
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(() => {
|
||||
@@ -206,13 +317,16 @@ const myTaskByCourse = computed(() => {
|
||||
|
||||
// 「我的课程」相关性口径(与后端推送口径一致):
|
||||
// ① 我有该课学习任务(线上必修按部门推送);② 我是该课讲师;
|
||||
// ③ 课程部门范围覆盖我(dept_ids 为空 = 全员可见,非空需包含我的部门)。
|
||||
// ③ 课程部门范围覆盖我(dept_ids 为空 = 全员可见,非空需包含我的部门);
|
||||
// ④ 我是该课场次参加人员(学员名单接口,线下课参加人员由此可见——此前参加
|
||||
// 人员只落名单与文案,不进任何"与我相关"判定,被设为参加人员却看不到课)。
|
||||
// 讲师匹配用平台用户 id(user_id)——与后端 course.LecturerID == callerUserID 同口径。
|
||||
const myUserId = computed(() => myProfile.value?.user_id || '')
|
||||
const isMyTeaching = (c: TrainingCourse) => !!myUserId.value && c.lecturer_id === myUserId.value
|
||||
const isMyCourse = (c: TrainingCourse) => {
|
||||
if (myTaskByCourse.value.has(c.id)) return true
|
||||
if (isMyTeaching(c)) return true
|
||||
if (myEnrolledCourseIds.value.has(c.id)) return true
|
||||
const scope = c.dept_ids || []
|
||||
if (!scope.length) return true
|
||||
return !!myProfile.value && scope.includes(myProfile.value.dept_id)
|
||||
@@ -243,6 +357,13 @@ const myCoursesSource = computed<TrainingCourse[]>(() => {
|
||||
// 待维护 = 我主讲且「草稿」状态的课程(2026-11 需求:待审/已发布缺课件不再计入统计)
|
||||
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
|
||||
|
||||
@@ -380,7 +501,9 @@ const visibleCards = computed<CatalogCard[]>(() => {
|
||||
}
|
||||
return list
|
||||
.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 unpublished = c.status !== 'published'
|
||||
// 「我的培训」角色标记:我主讲(优先) / 我参加,其余视图不标记
|
||||
@@ -441,17 +564,20 @@ const loadAll = async () => {
|
||||
// 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 id 过滤),
|
||||
// 供「我的培训」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
|
||||
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 统一走已发布课程口径(讲师账号的学习视角不受课程维护范围影响)
|
||||
listCourses({ page_size: 100, scope: 'student' }),
|
||||
listMyLearningTasks().catch(() => null),
|
||||
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
|
||||
getMyProfile().catch(() => null),
|
||||
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
|
||||
// 和信课程目录(000154):课程管理已发布课程
|
||||
listCourseLibrary({ page_size: 500 }).catch(() => null),
|
||||
// 和信课程目录(000160):scope=catalog —— 已发布 + 适合人员覆盖查看人
|
||||
// (全部/本部门;未设置沿用部门范围口径),不按维护角色收窄,全体员工同源
|
||||
listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => null),
|
||||
// 我的考试记录(000154)
|
||||
listMyExamRecords().catch(() => null),
|
||||
// 我经场次学员名单报名的课程 id(「我参加」判定;旧后端无此接口时回退空集)
|
||||
listMyEnrolledCourseIds().catch(() => null),
|
||||
])
|
||||
courses.value = unwrap(c)?.items || []
|
||||
myTasks.value = (t && unwrap(t)) || []
|
||||
@@ -460,6 +586,7 @@ const loadAll = async () => {
|
||||
lecturerCourses.value = (lc && unwrap(lc)?.items) || []
|
||||
libraryItems.value = (lib && unwrap(lib)?.items) || []
|
||||
myExamRecords.value = (exams && unwrap(exams)) || []
|
||||
myEnrolledCourseIds.value = new Set((enrolled && unwrap(enrolled)) || [])
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -556,6 +683,26 @@ onMounted(loadAll)
|
||||
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 {
|
||||
@@ -573,6 +720,26 @@ onMounted(loadAll)
|
||||
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 {
|
||||
font-weight: 600;
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
variant="text" theme="primary" size="small" :disabled="saving"
|
||||
@click="onPublish(row)"
|
||||
>发布</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 v-if="canManage" variant="text" theme="danger" size="small" @click="onDelete(row)">删除</t-button>
|
||||
</template>
|
||||
@@ -98,6 +98,14 @@
|
||||
</t-select>
|
||||
<div class="bank-hint">选择后带出课程信息且不可修改,仅可调整下方授课安排;还没有课程?<a class="template-link" href="javascript:void(0)" @click.prevent="goLibrary">前往「课程管理」新增</a></div>
|
||||
</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-input :value="formTypeDisplay" disabled />
|
||||
</t-form-item>
|
||||
@@ -195,16 +203,17 @@
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- 计划详情:计划编号展示 + 课程名称(课程管理选择,信息锁定) + 六项授课安排维护 -->
|
||||
<t-dialog v-model:visible="sessionsVisible" :header="`计划详情 · ${activeCourse?.name || ''}`" width="760" :footer="false">
|
||||
<!-- 计划调整:计划编号展示 + 课程名称/讲师(000161 可调整,讲师改动回写课程管理并重置待核验) + 六项授课安排维护 -->
|
||||
<t-dialog v-model:visible="sessionsVisible" :header="`计划调整 · ${activeCourse?.name || ''}`" width="760" :footer="false">
|
||||
<t-form label-width="90" class="detail-form">
|
||||
<t-form-item label="计划编号">
|
||||
<t-input :value="activeCourse?.plan_code || '-'" disabled />
|
||||
</t-form-item>
|
||||
<t-form-item label="课程名称">
|
||||
<!-- 未关联课程管理的计划可选定课程(选定后信息锁定);已关联直接锁定展示 -->
|
||||
<!-- 000161 可切换关联课程:改选即换 library_course_id,名称/类型随新课程带出
|
||||
(形式为计划侧独立字段,000162 起不随课程联动);讲师改动保存后回写
|
||||
课程管理并重置待核验,发布前须重新签核 -->
|
||||
<t-select
|
||||
v-if="!activeCourse?.library_course_id"
|
||||
v-model="editForm.library_course_id"
|
||||
:disabled="!canManage"
|
||||
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-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 label="类型">
|
||||
<t-input :value="formTypeDisplay" disabled />
|
||||
</t-form-item>
|
||||
<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 label="所属部门">
|
||||
<t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" />
|
||||
@@ -863,12 +889,12 @@ const form = ref({
|
||||
description: '',
|
||||
})
|
||||
|
||||
// 从课程管理选择课程:带出课程信息(类型/形式/讲师/学时/所属部门/说明)并锁定,
|
||||
// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员)
|
||||
// 从课程管理选择课程:带出课程信息(名称/类型/讲师/学时/所属部门/说明)并锁定,
|
||||
// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员);
|
||||
// 「形式」为计划侧独立字段(000162),不随所选课程带出,由表单自行选择
|
||||
const onLibraryCourseChange = (libraryCourseId: unknown) => {
|
||||
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
|
||||
form.value.name = lc?.name || ''
|
||||
form.value.mode = lc?.mode === 'online' ? 'online' : 'offline'
|
||||
form.value.type = lc?.type === 'elective' ? 'elective' : 'required'
|
||||
form.value.hours = lc?.hours || form.value.hours
|
||||
form.value.lecturer_id = lc?.lecturer_id || ''
|
||||
@@ -1159,19 +1185,40 @@ const onSave = async () => {
|
||||
}
|
||||
|
||||
const onPublish = async (row: TrainingCourse) => {
|
||||
// 与后端同口径的前置校验:线上必须有课件,线下必须有讲师
|
||||
// 与后端同口径的前置校验(000161):线上必须有课件;线下须有讲师(外部姓名
|
||||
// 亦可)/授课时间/授课地点;两者均须已设置参加人员且关联课程已签核
|
||||
if (row.mode === 'online') {
|
||||
try {
|
||||
const res = await listMaterials(row.id)
|
||||
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 {
|
||||
/* 查询失败时交由后端校验兜底 */
|
||||
}
|
||||
} else if (!row.lecturer_id) {
|
||||
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「详情」中指定讲师`)
|
||||
} else {
|
||||
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
|
||||
}
|
||||
try {
|
||||
@@ -1263,12 +1310,11 @@ const openDetail = async (row: TrainingCourse) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定,
|
||||
// 适用部门变化经 watcher 自动同步参加人员名单
|
||||
// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定(形式除外,
|
||||
// 000162 计划形式独立可改),适用部门变化经 watcher 自动同步参加人员名单
|
||||
const onDetailLibraryCourseChange = (libraryCourseId: unknown) => {
|
||||
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
|
||||
editForm.value.name = lc?.name || ''
|
||||
editForm.value.mode = lc?.mode === 'online' ? 'online' : 'offline'
|
||||
editForm.value.type = lc?.type === 'elective' ? 'elective' : 'required'
|
||||
editForm.value.hours = lc?.hours || editForm.value.hours
|
||||
editForm.value.lecturer_id = lc?.lecturer_id || ''
|
||||
@@ -1339,42 +1385,55 @@ const ensureCourseSession = async (
|
||||
// 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。
|
||||
// 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须
|
||||
// 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。
|
||||
const detailSavePayload = (row: TrainingCourse) => ({
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: editForm.value.name,
|
||||
mode: editForm.value.mode,
|
||||
type: editForm.value.type,
|
||||
hours: editForm.value.hours,
|
||||
credits: editForm.value.credits,
|
||||
exam_enabled: row.exam_enabled,
|
||||
dept_ids: editForm.value.dept_ids,
|
||||
lecturer_id: editForm.value.lecturer_id || undefined,
|
||||
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
|
||||
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
|
||||
description: row.description,
|
||||
material_ids: row.material_ids,
|
||||
tags: row.tags,
|
||||
status: row.status,
|
||||
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,
|
||||
lecturer_external: row.lecturer_external || '',
|
||||
remark: row.remark || '',
|
||||
// 课程管理关联(未关联的存量计划可在此选定课程;关联后服务端锁定带出字段)
|
||||
library_course_id: editForm.value.library_course_id || row.library_course_id || '',
|
||||
})
|
||||
// 000161 讲师解析:名册 id 直接用;非名册值(creatable 直接输入)按外部讲师姓名落库
|
||||
const resolveDetailLecturer = (row: TrainingCourse) => {
|
||||
const v = (editForm.value.lecturer_id || '').trim()
|
||||
if (!v) return { lecturerId: '', external: row.lecturer_external || '' }
|
||||
if (lecturers.value.some((l) => l.id === v)) return { lecturerId: v, external: '' }
|
||||
return { lecturerId: '', external: v }
|
||||
}
|
||||
|
||||
const detailSavePayload = (row: TrainingCourse) => {
|
||||
const lecturer = resolveDetailLecturer(row)
|
||||
return ({
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: editForm.value.name,
|
||||
mode: editForm.value.mode,
|
||||
type: editForm.value.type,
|
||||
hours: editForm.value.hours,
|
||||
credits: editForm.value.credits,
|
||||
exam_enabled: row.exam_enabled,
|
||||
dept_ids: editForm.value.dept_ids,
|
||||
lecturer_id: lecturer.lecturerId || undefined,
|
||||
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
|
||||
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
|
||||
description: row.description,
|
||||
material_ids: row.material_ids,
|
||||
tags: row.tags,
|
||||
status: row.status,
|
||||
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 row = activeCourse.value
|
||||
if (!row) return
|
||||
// 讲师随课程管理锁定:缺失时提示去课程管理维护(发布时后端也会强制校验)
|
||||
if (row.mode === 'offline' && !editForm.value.lecturer_id) {
|
||||
MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师')
|
||||
// 线下计划须指定讲师(名册 id 或外部姓名;发布时后端也会强制校验)
|
||||
const lecturer = resolveDetailLecturer(row)
|
||||
if (editForm.value.mode === 'offline' && !lecturer.lecturerId && !lecturer.external) {
|
||||
MessagePlugin.warning('线下计划需先指定讲师(从名册选择或输入外部讲师姓名)')
|
||||
return
|
||||
}
|
||||
detailSaving.value = true
|
||||
@@ -1388,7 +1447,7 @@ const onSaveDetail = async () => {
|
||||
await saveCourse(detailSavePayload(row))
|
||||
const sessionOpts = {
|
||||
mode: editForm.value.mode,
|
||||
lecturerId: editForm.value.lecturer_id || undefined,
|
||||
lecturerId: lecturer.lecturerId || undefined,
|
||||
startAt: editForm.value.start_at,
|
||||
location: editForm.value.location,
|
||||
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() : '',
|
||||
location: editForm.value.location,
|
||||
capacity: existing?.capacity ?? 0,
|
||||
lecturer_id: editForm.value.lecturer_id || undefined,
|
||||
lecturer_id: lecturer.lecturerId || undefined,
|
||||
// [2026-11 推学员] 编辑排课时同步通知方式
|
||||
notify_mode: editForm.value.notify_mode,
|
||||
})
|
||||
@@ -1426,8 +1485,8 @@ const onSaveDetail = async () => {
|
||||
)
|
||||
sessionsVisible.value = false
|
||||
loadAll()
|
||||
} catch {
|
||||
MessagePlugin.error('保存失败,请稍后重试')
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
|
||||
} finally {
|
||||
detailSaving.value = false
|
||||
}
|
||||
|
||||
@@ -29,9 +29,22 @@
|
||||
</t-select>
|
||||
<t-button variant="text" theme="primary" size="small" @click="resetFilters">重置</t-button>
|
||||
<span class="library-filter-count">共 {{ filteredItems.length }} 门</span>
|
||||
<!-- 批量操作(000157):核验/删除均仅课长/经理限本部门,且仅待核验行可删 -->
|
||||
<t-button
|
||||
v-if="canVerify" variant="outline" theme="primary" size="small"
|
||||
:disabled="!selectedKeys.length" :loading="batchSaving" @click="onBatchVerify"
|
||||
>批量核验</t-button>
|
||||
<t-button
|
||||
v-if="canDelete" variant="outline" theme="danger" size="small"
|
||||
:disabled="!selectedKeys.length" :loading="batchSaving" @click="onBatchDelete"
|
||||
>批量删除</t-button>
|
||||
<span v-if="selectedKeys.length" class="library-filter-count">已选 {{ selectedKeys.length }} 项</span>
|
||||
</div>
|
||||
|
||||
<t-table :data="filteredItems" :columns="columns" row-key="id" size="small" :loading="loading">
|
||||
<t-table
|
||||
v-model:selected-row-keys="selectedKeys"
|
||||
:data="filteredItems" :columns="columns" row-key="id" size="small" :loading="loading"
|
||||
>
|
||||
<template #code="{ row }">{{ row.code || '-' }}</template>
|
||||
<template #name="{ row }"><span class="clamp-2">{{ row.name }}</span></template>
|
||||
<template #description="{ row }">
|
||||
@@ -65,9 +78,14 @@
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<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="row.file_name" theme="success" variant="light" size="small" class="material-file-tag">附件</t-tag>
|
||||
<!-- 课件只展示有/无:有=已上传文件或已挂接知识库课件,点击直达课件管理抽屉 -->
|
||||
<t-tag v-if="hasMaterial(row)" theme="success" variant="light" size="small" class="cell-link" @click="openMaterialDrawer(row)">有</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 #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
|
||||
<!-- 创建人(联查 users):记录课程由谁录入 -->
|
||||
@@ -78,9 +96,23 @@
|
||||
variant="light" size="small"
|
||||
>{{ publishStatusText(row.publish_status) }}</t-tag>
|
||||
</template>
|
||||
<!-- 核验状态(000157):新增/编辑后待核验,课长/经理核验确认后方可发布 -->
|
||||
<template #verify_status="{ row }">
|
||||
<t-tag :theme="row.verify_status === 'confirmed' ? 'success' : 'warning'" variant="light" size="small">
|
||||
{{ row.verify_status === 'confirmed' ? '已确认' : '待核验' }}
|
||||
</t-tag>
|
||||
</template>
|
||||
<template #op="{ row }">
|
||||
<t-button v-if="canManage" 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-popconfirm
|
||||
v-if="canVerifyCourse(row)"
|
||||
content="核验确认后该课程方可发布,确认核验通过?" theme="primary"
|
||||
@confirm="onVerify(row)"
|
||||
>
|
||||
<t-button variant="text" theme="primary" size="small">核验</t-button>
|
||||
</t-popconfirm>
|
||||
<t-popconfirm
|
||||
v-if="canManage && row.publish_status !== 'published'"
|
||||
content="发布后该课程进入培训中心「和信课程」目录(本部门可见)。" theme="primary"
|
||||
@@ -95,10 +127,12 @@
|
||||
>
|
||||
<t-button variant="text" theme="danger" size="small">下线</t-button>
|
||||
</t-popconfirm>
|
||||
<t-popconfirm v-if="canManage" content="确定删除该课程?已创建的月培训计划不受影响。" theme="danger" @confirm="onDelete(row)">
|
||||
<t-popconfirm
|
||||
v-if="canDeleteCourse(row)"
|
||||
content="仅待核验状态的课程可删除,确定删除该课程?已创建的月培训计划不受影响。" theme="danger" @confirm="onDelete(row)"
|
||||
>
|
||||
<t-button variant="text" theme="danger" size="small">删除</t-button>
|
||||
</t-popconfirm>
|
||||
<t-button v-if="row.file_name" variant="text" size="small" @click="onDownloadMaterial(row)">下载课件</t-button>
|
||||
</template>
|
||||
</t-table>
|
||||
</div>
|
||||
@@ -113,8 +147,12 @@
|
||||
<t-input v-model="form.name" placeholder="请输入课程名称" />
|
||||
</t-form-item>
|
||||
<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-select>
|
||||
</t-form-item>
|
||||
@@ -122,8 +160,14 @@
|
||||
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
|
||||
</t-form-item>
|
||||
<t-form-item label="适合人员">
|
||||
<!-- 对应需求表「参加人员」:自由文本,如:财会人员 -->
|
||||
<t-input v-model="form.suitable_members" placeholder="适合参加的人员(选填),如:财会人员" />
|
||||
<!-- 000159 部门多选口径:归属部门(可多选)或「全部」(互斥);发布后
|
||||
培训中心按此展示给对应人员,存量自由文本值回显为选项 -->
|
||||
<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 label="分类">
|
||||
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
|
||||
@@ -152,50 +196,8 @@
|
||||
<t-form-item label="时长(学时)">
|
||||
<t-input-number v-model="form.hours" :min="0" :step="0.5" style="width: 100%" />
|
||||
</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>
|
||||
<div class="form-hint">分类选项由配置中心「课程分类」维护,支持手动输入保存;讲师可为员工名册内人员或外部讲师;月培训计划「课程名称」将从本页课程中选择并自动带出此处维护的信息(不可修改);试题经列表「试题」入口维护。</div>
|
||||
<div class="form-hint">分类选项由配置中心「课程分类」维护,支持手动输入保存;讲师可为员工名册内人员或外部讲师;月培训计划「课程名称」将从本页课程中选择并自动带出此处维护的信息(不可修改);课件上传/预览/下载经列表「课件」入口、试题经列表「试题」入口维护;发布课程前必须已上传课件。</div>
|
||||
<template #footer>
|
||||
<t-button variant="outline" @click="formVisible = false">取消</t-button>
|
||||
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
|
||||
@@ -219,6 +221,60 @@
|
||||
</template>
|
||||
</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 出题) -->
|
||||
<t-drawer
|
||||
v-model:visible="questionsVisible"
|
||||
@@ -439,7 +495,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
||||
@@ -467,9 +523,11 @@ import {
|
||||
listQuestions,
|
||||
offlineCourseLibraryItem,
|
||||
publishCourseLibraryItem,
|
||||
removeCourseLibraryMaterial,
|
||||
saveCourseLibraryItem,
|
||||
saveQuestion,
|
||||
uploadCourseLibraryMaterial,
|
||||
verifyCourseLibraryItems,
|
||||
type TrainingDept,
|
||||
type TrainingLibraryCourse,
|
||||
type TrainingMember,
|
||||
@@ -479,7 +537,8 @@ import {
|
||||
} from '@/api/training'
|
||||
|
||||
const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
||||
// 课程维护:人事/课长/讲师(roles 已按权限组展开,经理经课长继承自动命中)
|
||||
// 课程维护(新增/编辑/发布/导入/导出):人事/课长/讲师(roles 已按权限组展开,
|
||||
// 经理经课长继承自动命中)。人事无核验/删除权限(000157)。
|
||||
const canManage = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor' || r === 'lecturer'))
|
||||
|
||||
const loading = ref(false)
|
||||
@@ -492,6 +551,56 @@ const depts = ref<TrainingDept[]>([])
|
||||
const configCategories = ref<string[]>([])
|
||||
// 本人所在部门 id:新增课程「所属部门」默认当前登录用户所在部门(getMyProfile)
|
||||
const myDeptId = ref('')
|
||||
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
|
||||
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):严格限「本部门课长/经理」——人事/空间管理员一律无
|
||||
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
|
||||
const canVerify = computed(() => props.roles.includes('supervisor'))
|
||||
const canDelete = canVerify
|
||||
// 仅本部门「待核验」课程可核验/删除;与后端 callerVerifyDeptScope 同口径:
|
||||
// 无部门身份或课程所属部门与本人不一致时一律不可操作。
|
||||
const canVerifyCourse = (row: TrainingLibraryCourse) =>
|
||||
canVerify.value &&
|
||||
row.verify_status === 'pending' &&
|
||||
Boolean(myDeptId.value) &&
|
||||
Boolean(row.owner_dept_id) &&
|
||||
row.owner_dept_id === myDeptId.value
|
||||
const canDeleteCourse = canVerifyCourse
|
||||
|
||||
// 编辑权限:维护角色可编辑可见课程;无维护角色的学员仅可编辑「与我相关」课程
|
||||
// (本人创建或本人授课,后端兜底校验同口径)
|
||||
const canEditCourse = (row: TrainingLibraryCourse) =>
|
||||
canManage.value ||
|
||||
(Boolean(myUserId.value) && (row.creator_id === myUserId.value || row.lecturer_id === myUserId.value))
|
||||
|
||||
// ---- 查询条件(编号/名称/分类/类型/形式;列表全量加载,本地过滤) ----
|
||||
const filters = ref({ keyword: '', category: '', type: '', mode: '' })
|
||||
@@ -520,6 +629,8 @@ const filteredItems = computed(() => {
|
||||
})
|
||||
|
||||
const columns = [
|
||||
// 批量勾选列(000157):配合批量核验/批量删除
|
||||
{ colKey: 'row-select', type: 'multiple', width: 44 },
|
||||
// 左侧列不固定(000154):课程编号/课程名称随横向滚动,操作仍固定右侧
|
||||
{ colKey: 'code', title: '课程编号', width: 105 },
|
||||
{ colKey: 'name', title: '课程名称', width: 170 },
|
||||
@@ -531,13 +642,17 @@ const columns = [
|
||||
{ colKey: 'mode', title: '线上/线下', width: 92 },
|
||||
{ colKey: 'lecturer', title: '讲师', width: 110 },
|
||||
{ colKey: 'hours', title: '时长', width: 84 },
|
||||
{ colKey: 'material', title: '课件', minWidth: 150 },
|
||||
// 课件/试题只展示有/无:有=已上传课件或已关联题库,点击直达对应维护抽屉
|
||||
{ colKey: 'material', title: '课件', width: 70 },
|
||||
{ colKey: 'question', title: '试题', width: 70 },
|
||||
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
|
||||
{ colKey: 'publish_status', title: '发布状态', width: 90 },
|
||||
{ colKey: 'created_at', title: '创建时间', width: 140 },
|
||||
// 创建人(联查 users):记录课程录入人员
|
||||
{ colKey: 'creator_name', title: '创建人', width: 96 },
|
||||
{ colKey: 'op', title: '操作', width: 280, fixed: 'right' },
|
||||
// 核验状态(000157):固定右侧置于操作列前
|
||||
{ colKey: 'verify_status', title: '状态', width: 90, fixed: 'right' },
|
||||
{ colKey: 'op', title: '操作', width: 340, fixed: 'right' },
|
||||
]
|
||||
|
||||
const lecturerText = (row: TrainingLibraryCourse) =>
|
||||
@@ -558,7 +673,10 @@ const loadAll = async () => {
|
||||
members.value = (m && unwrap(m)?.items) || []
|
||||
depts.value = (d && unwrap(d)) || []
|
||||
configCategories.value = cats
|
||||
myDeptId.value = (me && unwrap(me)?.dept_id) || ''
|
||||
const meBody = me && unwrap(me)
|
||||
myDeptId.value = meBody?.dept_id || ''
|
||||
myUserId.value = meBody?.user_id || ''
|
||||
meDeptName.value = meBody?.dept_name || ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -567,7 +685,9 @@ const loadAll = async () => {
|
||||
// ---- 新增/编辑 ----
|
||||
|
||||
const formVisible = ref(false)
|
||||
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析
|
||||
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析。
|
||||
// material_name 为隐藏保留字段:课件维护移至「课件」抽屉后,编辑保存仍原值回传,
|
||||
// 防止全量更新把名称登记误清(000162)。
|
||||
const form = ref({
|
||||
id: '',
|
||||
code: '',
|
||||
@@ -577,43 +697,19 @@ const form = ref({
|
||||
suitable_members: '',
|
||||
category: '',
|
||||
type: 'required' as 'required' | 'elective',
|
||||
mode: 'offline' as 'offline' | 'online',
|
||||
// 新增默认「线上」(000162):线上课为常规形态;编辑随原值
|
||||
mode: 'online' as 'offline' | 'online',
|
||||
lecturer: '',
|
||||
hours: 0,
|
||||
material_name: '',
|
||||
file_name: '',
|
||||
clear_file: false,
|
||||
})
|
||||
// 待上传课件文件(保存成功后随行上传)
|
||||
const materialInputRef = ref<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 kbDocsLoading = ref(false)
|
||||
const coursewareKbRef = ref<{ id: string; name: string } | null>(null)
|
||||
let kbDocsLoaded = false
|
||||
|
||||
const toggleKbDocSelect = async () => {
|
||||
kbSelectVisible.value = !kbSelectVisible.value
|
||||
if (kbSelectVisible.value) await loadCoursewareKbDocs()
|
||||
}
|
||||
|
||||
// 拉取「企业培训(课件)」知识库文档列表(惰性加载一次)
|
||||
const loadCoursewareKbDocs = async () => {
|
||||
if (kbDocsLoaded) return
|
||||
@@ -641,24 +737,6 @@ const loadCoursewareKbDocs = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const confirmKbDoc = () => {
|
||||
const doc = kbDocs.value.find((d) => d.id === pendingKbDocId.value)
|
||||
if (!doc) {
|
||||
MessagePlugin.warning('请先选择知识库课件文档')
|
||||
return
|
||||
}
|
||||
pendingKbDoc.value = { id: doc.id, name: doc.file_name }
|
||||
// 与上传文件互斥:选定知识库文档即清掉待上传文件与已有文件移除标记
|
||||
clearPendingMaterialFile()
|
||||
form.value.clear_file = false
|
||||
kbSelectVisible.value = false
|
||||
}
|
||||
|
||||
const clearPendingKbDoc = () => {
|
||||
pendingKbDoc.value = null
|
||||
pendingKbDocId.value = ''
|
||||
}
|
||||
|
||||
// 讲师下拉选项:全体员工(id=平台用户 id,与课程/需求讲师字段口径一致);
|
||||
// 编辑外部讲师(非 id 值)时追加临时选项避免回显裸文本丢失
|
||||
const lecturerSelectOptions = computed(() => {
|
||||
@@ -673,26 +751,25 @@ const lecturerSelectOptions = computed(() => {
|
||||
})
|
||||
|
||||
const openForm = (row?: TrainingLibraryCourse) => {
|
||||
clearPendingMaterialFile()
|
||||
clearPendingKbDoc()
|
||||
kbSelectVisible.value = false
|
||||
form.value = {
|
||||
id: row?.id || '',
|
||||
code: row?.code || '',
|
||||
name: row?.name || '',
|
||||
// 新增默认当前登录用户所在部门;编辑保持原部门
|
||||
// 新增默认当前登录用户所在部门(锁定不可改);编辑保持原部门
|
||||
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
||||
description: row?.description || '',
|
||||
suitable_members: row?.suitable_members || '',
|
||||
// 适合人员(000160):新增默认创建人所属部门名,可改「全部」或其他部门
|
||||
suitable_members: row?.suitable_members || (row ? '' : myDeptName.value),
|
||||
category: row?.category || '',
|
||||
type: row?.type === 'elective' ? 'elective' : 'required',
|
||||
mode: row?.mode === 'online' ? 'online' : 'offline',
|
||||
// 新增默认「线上」(000162);编辑随原值
|
||||
mode: row ? (row.mode === 'online' ? 'online' : 'offline') : 'online',
|
||||
lecturer: row?.lecturer_id || row?.lecturer_external || '',
|
||||
hours: row?.hours || 0,
|
||||
material_name: row?.material_name || '',
|
||||
file_name: row?.file_name || '',
|
||||
clear_file: false,
|
||||
}
|
||||
// 适合人员多选回显(000159):落库串「、」join → 数组;新增默认本部门
|
||||
suitableList.value = splitSuitable(form.value.suitable_members)
|
||||
formVisible.value = true
|
||||
}
|
||||
|
||||
@@ -712,6 +789,8 @@ const onSave = async () => {
|
||||
saving.value = true
|
||||
try {
|
||||
const lecturer = resolveLecturer(form.value.lecturer.trim())
|
||||
// 适合人员多选 → 「、」join 落库(000159);「全部」与部门互斥由 watch 保证
|
||||
form.value.suitable_members = suitableList.value.join('、')
|
||||
const res = await saveCourseLibraryItem({
|
||||
id: form.value.id || undefined,
|
||||
name: form.value.name.trim(),
|
||||
@@ -724,21 +803,10 @@ const onSave = async () => {
|
||||
lecturer_id: lecturer.lecturer_id || undefined,
|
||||
lecturer_external: lecturer.lecturer_external || undefined,
|
||||
hours: form.value.hours,
|
||||
// 隐藏保留字段:课件维护已移至「课件」抽屉,编辑保存原值回传防误清(000162)
|
||||
material_name: form.value.material_name.trim(),
|
||||
clear_file: form.value.clear_file || undefined,
|
||||
})
|
||||
const saved = unwrap(res)
|
||||
// 待上传课件文件:条目已落库后随行上传(名称登记为空时后端以文件名兜底;
|
||||
// 文档类自动同步知识库「企业培训(课件)」,支持 AI 对话与出题)
|
||||
if (pendingMaterialFile.value && saved?.id) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', pendingMaterialFile.value)
|
||||
await uploadCourseLibraryMaterial(saved.id, fd)
|
||||
}
|
||||
// 从知识库选择的课件:保存后挂接知识库文档(与上传同步同口径)
|
||||
if (pendingKbDoc.value && saved?.id) {
|
||||
await attachCourseLibraryMaterialFromKb(saved.id, { knowledge_id: pendingKbDoc.value.id })
|
||||
}
|
||||
MessagePlugin.success(
|
||||
form.value.id
|
||||
? saved?.code
|
||||
@@ -749,8 +817,6 @@ const onSave = async () => {
|
||||
: '课程已创建,可在「月培训计划」中引用',
|
||||
)
|
||||
formVisible.value = false
|
||||
clearPendingMaterialFile()
|
||||
clearPendingKbDoc()
|
||||
loadAll()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
|
||||
@@ -769,12 +835,85 @@ const onDelete = async (row: TrainingLibraryCourse) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 发布状态展示文案(000154)
|
||||
// ---- 核验(000157):待核验 → 已确认,单个/批量共用核验端点(仅课长/经理限本部门) ----
|
||||
const selectedKeys = ref<string[]>([])
|
||||
const batchSaving = ref(false)
|
||||
|
||||
const onVerify = async (row: TrainingLibraryCourse) => {
|
||||
try {
|
||||
await verifyCourseLibraryItems([row.id])
|
||||
row.verify_status = 'confirmed'
|
||||
MessagePlugin.success(`课程「${row.name}」已核验确认,可发布`)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(apiErrorMessage(e, '核验失败'))
|
||||
}
|
||||
}
|
||||
|
||||
const onBatchVerify = async () => {
|
||||
// 与后端口径一致:仅本部门待核验行提交,已确认/越权行直接跳过
|
||||
const rows = filteredItems.value.filter(
|
||||
(r) => selectedKeys.value.includes(r.id) && r.verify_status !== 'confirmed' && canVerifyCourse(r),
|
||||
)
|
||||
if (!rows.length) {
|
||||
MessagePlugin.warning('请先勾选本部门待核验状态的课程')
|
||||
return
|
||||
}
|
||||
batchSaving.value = true
|
||||
try {
|
||||
const { verified, skipped } = unwrap(await verifyCourseLibraryItems(rows.map((r) => r.id)))
|
||||
MessagePlugin.success(`批量核验完成:成功 ${verified} 条${skipped ? `,跳过 ${skipped} 条` : ''}`)
|
||||
selectedKeys.value = []
|
||||
loadAll()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(apiErrorMessage(e, '批量核验失败'))
|
||||
} finally {
|
||||
batchSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const onBatchDelete = async () => {
|
||||
// 与后端口径一致:仅本部门待核验行提交(已确认/越权行跳过)
|
||||
const rows = filteredItems.value.filter((r) => selectedKeys.value.includes(r.id) && canDeleteCourse(r))
|
||||
if (!rows.length) {
|
||||
MessagePlugin.warning('请先勾选本部门待核验状态的课程')
|
||||
return
|
||||
}
|
||||
batchSaving.value = true
|
||||
let ok = 0
|
||||
let fail = 0
|
||||
try {
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await deleteCourseLibraryItem(row.id)
|
||||
ok += 1
|
||||
} catch {
|
||||
fail += 1
|
||||
}
|
||||
}
|
||||
MessagePlugin.success(`批量删除完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''}`)
|
||||
selectedKeys.value = []
|
||||
loadAll()
|
||||
} finally {
|
||||
batchSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 发布状态展示文案(000154;000157 起草稿文案调整为「待发布」)
|
||||
const publishStatusText = (status?: string) =>
|
||||
({ published: '已发布', offline: '已下线', draft: '草稿' }[status || 'draft'] || '草稿')
|
||||
({ published: '已发布', offline: '已下线', draft: '待发布' }[status || 'draft'] || '待发布')
|
||||
|
||||
// 发布/下线(000154):发布后进入培训中心「和信课程」目录,下线即从目录撤回
|
||||
const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published' | 'offline') => {
|
||||
// 发布前置校验(000157):仅「已确认」课程可发布(后端兜底同样拦截)
|
||||
if (status === 'published' && row.verify_status !== 'confirmed') {
|
||||
MessagePlugin.warning('该课程尚未核验,请先由本部门课长/经理核验确认后再发布')
|
||||
return
|
||||
}
|
||||
// 发布前置校验(000162):必须有课件(名称登记不算,后端兜底同样拦截)
|
||||
if (status === 'published' && !hasMaterial(row)) {
|
||||
MessagePlugin.warning('该课程尚未上传课件,请先在「课件」入口上传课件文件(或从知识库选择)后再发布')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const updated = unwrap(
|
||||
status === 'published' ? await publishCourseLibraryItem(row.id) : await offlineCourseLibraryItem(row.id),
|
||||
@@ -793,7 +932,11 @@ const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published
|
||||
}
|
||||
}
|
||||
|
||||
const onDownloadMaterial = async (row: TrainingLibraryCourse) => {
|
||||
// 课件有无口径:已上传原始文件或已挂接知识库课件文档(名称登记不算,与发布校验同口径)
|
||||
const hasMaterial = (row: TrainingLibraryCourse) => Boolean(row.file_name || row.knowledge_id)
|
||||
|
||||
const onDownloadMaterial = async (row: TrainingLibraryCourse | null) => {
|
||||
if (!row) return
|
||||
try {
|
||||
// getDown 直接返回 Blob(trainingTemplates 同款消费方式)
|
||||
const blob = await downloadCourseLibraryMaterial(row.id)
|
||||
@@ -808,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 () => {
|
||||
@@ -1025,6 +1304,10 @@ const loadBanks = async () => {
|
||||
try {
|
||||
const res = await listLibraryCourseQuestionBanks(course.id)
|
||||
banks.value = unwrap(res) || []
|
||||
// 题库增删后同步列表「试题」有/无计数(该端点即本课程全部题库)
|
||||
course.question_bank_count = banks.value.length
|
||||
const idx = items.value.findIndex((it) => it.id === course.id)
|
||||
if (idx >= 0) items.value[idx].question_bank_count = banks.value.length
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(apiErrorMessage(e, '题库加载失败'))
|
||||
} finally {
|
||||
@@ -1209,7 +1492,7 @@ const onGenerateQuestions = async () => {
|
||||
const course = questionsCourse.value
|
||||
if (!course) return
|
||||
if (!course.knowledge_id) {
|
||||
MessagePlugin.warning('该课程课件未同步知识库,请先在课程表单中上传课件文档后再 AI 出题')
|
||||
MessagePlugin.warning('该课程课件未同步知识库,请先在「课件」入口上传课件文档后再 AI 出题')
|
||||
return
|
||||
}
|
||||
genLoading.value = true
|
||||
@@ -1412,39 +1695,9 @@ onMounted(loadAll)
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
// 课件字段:名称登记 + 文件上传行
|
||||
.material-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.material-upload-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.material-upload-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.material-file-name {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.material-placeholder {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.material-file-tag {
|
||||
margin-left: 6px;
|
||||
// 列表「有」标签可点击直达维护抽屉
|
||||
.cell-link {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// 批量导入弹窗:模板下载 + Excel 上传一行排布(与培训计划导入同款)
|
||||
|
||||
@@ -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})` : ''}`"
|
||||
/>
|
||||
</t-select>
|
||||
<!-- 000158:提交时按名称精准匹配课程管理,未命中自动新增待核验课程 -->
|
||||
<div class="form-hint">提交时按名称精准匹配课程管理;未匹配到将自动新增该课程(待审核),经课长/经理签核后方可发布</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="分类" name="category">
|
||||
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
|
||||
</t-form-item>
|
||||
<t-form-item label="所属部门" name="dept_id">
|
||||
<t-input :value="deptDisplay" disabled placeholder="提交时按提报人所在部门自动获取" />
|
||||
<!-- 000158:所属部门必须为填报人本人部门,服务端强制按提报人部门落库 -->
|
||||
<t-input :value="deptDisplay" disabled placeholder="自动带出提报人所在部门(不可修改)" />
|
||||
</t-form-item>
|
||||
<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 label="计划培训月份" name="planned_month">
|
||||
<t-select
|
||||
@@ -197,7 +206,7 @@
|
||||
:autosize="{ minRows: 6 }"
|
||||
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
|
||||
/>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配)或外部讲师姓名;部门列必须为导入人本人部门,留空默认本人部门,其余部门整批拒绝导入;课程按名称精准匹配课程管理,未匹配到自动新增该课程(待审核);导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
|
||||
</template>
|
||||
@@ -235,7 +244,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
@@ -332,13 +341,35 @@ const demandForm = ref({
|
||||
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):分类/适合人员/讲师随课程回填,均可再改;
|
||||
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
|
||||
const onDemandCourseChange = (name: unknown) => {
|
||||
const course = libraryCourses.value.find((c) => c.name === name)
|
||||
if (!course) return
|
||||
demandForm.value.category = course.category || ''
|
||||
if (course.suitable_members) demandForm.value.post_scope = course.suitable_members
|
||||
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 || ''
|
||||
if (lecturerValue) {
|
||||
if (!lecturers.value.some((l) => l.id === lecturerValue)) {
|
||||
@@ -552,6 +583,7 @@ const onOpenDemandForm = () => {
|
||||
lecturer: '',
|
||||
remark: '',
|
||||
}
|
||||
demandSuitableList.value = []
|
||||
demandFormVisible.value = true
|
||||
}
|
||||
|
||||
@@ -588,6 +620,8 @@ const onEditDemand = (row: TrainingDemand) => {
|
||||
lecturer: lecturerValue,
|
||||
remark: row.remark || '',
|
||||
}
|
||||
// 适合人员多选回显(000159):落库串「、」join → 数组
|
||||
demandSuitableList.value = splitSuitable(demandForm.value.post_scope)
|
||||
demandFormVisible.value = true
|
||||
}
|
||||
|
||||
@@ -599,10 +633,14 @@ const onSaveDemand = async () => {
|
||||
saving.value = true
|
||||
try {
|
||||
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
|
||||
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名
|
||||
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名;
|
||||
// 适合人员多选 → 「、」join 落库(000159)
|
||||
const { lecturer, planned_month, ...rest } = demandForm.value
|
||||
rest.post_scope = demandSuitableList.value.join('、')
|
||||
const month = Number(planned_month) || 0
|
||||
const isEdit = Boolean(demandForm.value.id)
|
||||
// 课程管理中是否已有同名课程(000158:无则提交时自动新增待核验课程)
|
||||
const courseExisted = libraryCourses.value.some((c) => c.name === demandForm.value.course_name)
|
||||
await saveDemand({
|
||||
...rest,
|
||||
...resolveLecturer(lecturer),
|
||||
@@ -612,7 +650,13 @@ const onSaveDemand = async () => {
|
||||
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
|
||||
year: selectedYear.value,
|
||||
})
|
||||
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待核验')
|
||||
MessagePlugin.success(
|
||||
demandForm.value.id
|
||||
? '需求已更新'
|
||||
: courseExisted
|
||||
? '需求已提交,待核验'
|
||||
: `需求已提交,待核验;课程《${demandForm.value.course_name}》已自动新增到课程管理(待审核)`,
|
||||
)
|
||||
demandFormVisible.value = false
|
||||
loadAll()
|
||||
} catch (e: any) {
|
||||
@@ -668,8 +712,9 @@ const onImportDemands = async () => {
|
||||
importDemandsVisible.value = false
|
||||
importDemandsText.value = ''
|
||||
loadAll()
|
||||
} catch {
|
||||
MessagePlugin.error('导入失败,请检查格式')
|
||||
} catch (e: any) {
|
||||
// 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
|
||||
MessagePlugin.error(apiErrorMessage(e, '导入失败,请检查格式'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -747,7 +792,8 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
let skippedRows = 0
|
||||
let lecturerHits = 0
|
||||
let externalLecturers = 0
|
||||
let deptFromLecturer = 0
|
||||
// 部门口径(000158):Excel 全部行必须为导入人本人部门,前端预检不过不提交
|
||||
const deptViolations: string[] = []
|
||||
// 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案),
|
||||
// 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示
|
||||
const ensureMembers = async () => {
|
||||
@@ -763,24 +809,23 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
}
|
||||
}
|
||||
await ensureMembers()
|
||||
dataRows.forEach((row) => {
|
||||
dataRows.forEach((row, idx) => {
|
||||
const courseName = (row['课程名称'] || '').trim()
|
||||
if (!courseName) {
|
||||
skippedRows += 1
|
||||
return
|
||||
}
|
||||
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;未匹配留空
|
||||
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;
|
||||
// 000158:行部门必须为导入人本人部门——非空但未匹配到、或与本人部门
|
||||
// 不一致即记违规,整批拒绝;部门列留空的行由后端默认导入人部门。
|
||||
let deptId = ''
|
||||
let deptMatched = false
|
||||
const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim()
|
||||
if (deptName) {
|
||||
const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
|
||||
if (hit) {
|
||||
deptId = hit.id
|
||||
deptMatched = true
|
||||
}
|
||||
if (hit) deptId = hit.id
|
||||
if (!deptId || deptId !== myDeptId.value) deptViolations.push(`第${idx + 1}行(${deptName})`)
|
||||
}
|
||||
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名,行内部门未匹配时带出讲师部门;
|
||||
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名;
|
||||
// 非系统员工→落外部讲师姓名,讲师列照常显示
|
||||
let lecturerId = ''
|
||||
let lecturerExternal = ''
|
||||
@@ -790,10 +835,6 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
if (hit && hit.user_id) {
|
||||
lecturerId = hit.user_id
|
||||
lecturerHits += 1
|
||||
if (!deptMatched && hit.dept_id) {
|
||||
deptId = hit.dept_id
|
||||
deptFromLecturer += 1
|
||||
}
|
||||
} else {
|
||||
lecturerExternal = lecturerName
|
||||
externalLecturers += 1
|
||||
@@ -813,6 +854,7 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
lecturer_id: lecturerId,
|
||||
lecturer_external: lecturerExternal || undefined,
|
||||
dept_id: deptId,
|
||||
dept_name: deptName || undefined,
|
||||
planned_time: plannedMonth.planned || undefined,
|
||||
expect_month: plannedMonth.month || undefined,
|
||||
remark: (row['备注'] || '').trim(),
|
||||
@@ -822,24 +864,36 @@ const onImportDemandExcel = async (e: Event) => {
|
||||
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
|
||||
return
|
||||
}
|
||||
// 000158:存在非本人部门的行时整批拒绝(后端同口径兜底校验)
|
||||
if (deptViolations.length) {
|
||||
MessagePlugin.error(
|
||||
`导入失败:${deptViolations.join('、')}部门与您所在部门(${myDeptName.value || '未知'})不一致,仅可导入本人部门的需求表`,
|
||||
)
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
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(
|
||||
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
|
||||
(lecturerHits || externalLecturers
|
||||
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
|
||||
: '') +
|
||||
(deptFromLecturer ? `(其中 ${deptFromLecturer} 条部门按讲师带出)` : '') +
|
||||
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
|
||||
(imported?.courses_created ? `,自动新增待审核课程 ${imported.courses_created} 门` : '') +
|
||||
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
|
||||
)
|
||||
importDemandsVisible.value = false
|
||||
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
|
||||
if (titleYear !== selectedYear.value) selectedYear.value = titleYear
|
||||
loadAll()
|
||||
} catch {
|
||||
MessagePlugin.error('导入失败,请稍后重试')
|
||||
} catch (e: any) {
|
||||
// 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
|
||||
MessagePlugin.error(apiErrorMessage(e, '导入失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
有效期至 {{ fmtTime(signCode.expire_at) }}
|
||||
<template v-if="signCode.geo_radius"> · 定位半径 {{ signCode.geo_radius }}m</template>
|
||||
</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">
|
||||
{{ signCode ? '刷新签到码' : '生成签到码' }}
|
||||
</t-button>
|
||||
@@ -59,6 +65,15 @@
|
||||
<div class="upload-card__hint">{{ uploading ? '上传中…' : '课程实录留证 · 每个 ≤ ' + VIDEO_MAX_MB + 'MB' }}</div>
|
||||
</div>
|
||||
</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>
|
||||
<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')" />
|
||||
@@ -150,8 +165,8 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import QRCode from 'qrcode'
|
||||
import {
|
||||
@@ -182,6 +197,7 @@ import { fmtBeijingTime } from '@/utils/datetime'
|
||||
|
||||
const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
// 签到复核/代签:人事/课长(roles 已按权限组展开,经理自动命中)
|
||||
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 courses = ref<TrainingCourse[]>([])
|
||||
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 summary = ref<SignSummary | null>(null)
|
||||
const records = ref<TrainingSignRecord[]>([])
|
||||
@@ -236,6 +261,60 @@ const buildSignQr = async () => {
|
||||
}
|
||||
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 courseName = (courseId: string) => courses.value.find((c) => c.id === courseId)?.name || '课程'
|
||||
@@ -464,7 +543,11 @@ watch(() => route.query.courseId, applyRouteCourse)
|
||||
onMounted(async () => {
|
||||
await loadAll()
|
||||
applyRouteCourse()
|
||||
// 签到码轮换:进页即启动(选中场次后 watch 也会重启,双保险覆盖异步加载)。
|
||||
startCodeRotation()
|
||||
})
|
||||
|
||||
onUnmounted(stopCodeRotation)
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -518,6 +601,15 @@ onMounted(async () => {
|
||||
padding: 8px;
|
||||
}
|
||||
&__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 {
|
||||
|
||||
@@ -65,15 +65,25 @@ func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, i
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// 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 {
|
||||
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.DeptID != "" {
|
||||
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
||||
}
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("org_employees.employee_no ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
||||
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
||||
// 按姓名/工号/部门名/岗位模糊查找;姓名取真实姓名(display_name)
|
||||
// 回退平台账号(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
|
||||
@@ -102,9 +112,7 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
|
||||
tx := filter().
|
||||
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
||||
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
||||
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")
|
||||
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`)
|
||||
if moduleKey != "" {
|
||||
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
||||
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)
|
||||
}
|
||||
var employees []*types.OrgEmployee
|
||||
// 新增成员置顶(时间倒序):最新建档/导入的员工排在列表最前。
|
||||
err := tx.
|
||||
Order("org_employees.created_at ASC").
|
||||
Order("org_employees.created_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&employees).Error
|
||||
return employees, total, err
|
||||
@@ -141,6 +150,27 @@ func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID
|
||||
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).
|
||||
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||
if len(employees) == 0 {
|
||||
@@ -207,6 +237,7 @@ func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("users u").
|
||||
Select(`u.id, u.username, u.email, u.display_name,
|
||||
u.dept_code, u.dept_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).
|
||||
@@ -217,6 +248,31 @@ func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint
|
||||
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
|
||||
// given user IDs within the tenant — used to backfill employee_no on import
|
||||
// (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。
|
||||
@@ -243,6 +299,26 @@ func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantI
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 学习/积分/规则/通知
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -23,6 +23,29 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("tr_course_library.name ILIKE ?", "%"+q.Keyword+"%")
|
||||
}
|
||||
// 数据范围过滤(handler 按调用方角色强制注入,000157):dept_id=课长/经理
|
||||
// 本部门;related_user_id=无维护角色的用户仅见自己创建或授课的课程。
|
||||
if q.DeptID != "" {
|
||||
tx = tx.Where("tr_course_library.owner_dept_id = ?", q.DeptID)
|
||||
}
|
||||
if 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
|
||||
if err := tx.Count(&total).Error; err != nil {
|
||||
@@ -40,8 +63,10 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
var items []*types.TrainingCourseLibrary
|
||||
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id);
|
||||
// creator_name 联查创建人姓名(display_name 优先,回退 username 工号)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name").
|
||||
// creator_name 联查创建人姓名(display_name 优先,回退 username 工号);
|
||||
// question_bank_count 关联题库数(相关子查询,软删不计;列表「试题」有/无)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name, "+
|
||||
"(SELECT COUNT(*) FROM tr_question_banks qb WHERE qb.library_course_id = tr_course_library.id AND qb.tenant_id = tr_course_library.tenant_id AND qb.deleted_at IS NULL) AS question_bank_count").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
|
||||
@@ -51,6 +76,19 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
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.
|
||||
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||
var item types.TrainingCourseLibrary
|
||||
@@ -92,9 +130,30 @@ func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *
|
||||
"file_size": item.FileSize,
|
||||
// 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。
|
||||
"knowledge_id": item.KnowledgeID,
|
||||
// 核验状态(000157):编辑/换课件后由服务层重置为待核验并清空核验痕迹。
|
||||
"verify_status": item.VerifyStatus,
|
||||
"confirmed_by": item.ConfirmedBy,
|
||||
"confirmed_at": item.ConfirmedAt,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// ConfirmCourseLibraryItems 批量核验课程条目(000157):仅待核验行置为已确认并
|
||||
// 回填核验人/时间(幂等:已确认行不重复更新),返回实际核验行数。
|
||||
func (r *trainingRepository) ConfirmCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID string) (int64, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
tx := r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).
|
||||
Where("tenant_id = ? AND id IN ? AND verify_status = ?", tenantID, ids, types.CourseLibraryVerifyPending).
|
||||
Updates(map[string]interface{}{
|
||||
"verify_status": types.CourseLibraryVerifyConfirmed,
|
||||
"confirmed_by": verifierID,
|
||||
"confirmed_at": time.Now(),
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
return tx.RowsAffected, tx.Error
|
||||
}
|
||||
|
||||
// UpdateCourseLibraryPublishStatus 更新课程管理条目发布状态(000154):
|
||||
// published 已发布 / offline 已下线,供培训中心「和信课程」目录过滤。
|
||||
func (r *trainingRepository) UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
|
||||
|
||||
@@ -119,6 +119,7 @@ func (r *trainingRepository) UpdateDemand(ctx context.Context, demand *types.Tra
|
||||
"lecturer_id": demand.LecturerID,
|
||||
"lecturer_external": demand.LecturerExternal,
|
||||
"course_name": demand.CourseName,
|
||||
"library_course_id": demand.LibraryCourseID,
|
||||
"plant": demand.Plant,
|
||||
"category": demand.Category,
|
||||
"session_count": demand.SessionCount,
|
||||
@@ -527,6 +528,31 @@ func (r *trainingRepository) CountEnrolledMembersByCourse(ctx context.Context, t
|
||||
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 按课程聚合签到/线上学习/考试参与成员(去重成员集合):
|
||||
// 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷
|
||||
// (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.
|
||||
// 2026-11 轮换需求:轮换时新行携带 prev_token/prev_expire_at(旧码宽限用),
|
||||
// 一并覆盖,旧 token 即时退出当前码位。
|
||||
func (r *trainingRepository) UpsertSignCode(ctx context.Context, code *types.TrainingSignCode) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "session_id"}},
|
||||
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||
"token": gorm.Expr("EXCLUDED.token"),
|
||||
"expire_at": gorm.Expr("EXCLUDED.expire_at"),
|
||||
"geo_lat": gorm.Expr("EXCLUDED.geo_lat"),
|
||||
"geo_lng": gorm.Expr("EXCLUDED.geo_lng"),
|
||||
"geo_radius": gorm.Expr("EXCLUDED.geo_radius"),
|
||||
"created_by": gorm.Expr("EXCLUDED.created_by"),
|
||||
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||
"token": gorm.Expr("EXCLUDED.token"),
|
||||
"expire_at": gorm.Expr("EXCLUDED.expire_at"),
|
||||
"prev_token": gorm.Expr("EXCLUDED.prev_token"),
|
||||
"prev_expire_at": gorm.Expr("EXCLUDED.prev_expire_at"),
|
||||
"geo_lat": gorm.Expr("EXCLUDED.geo_lat"),
|
||||
"geo_lng": gorm.Expr("EXCLUDED.geo_lng"),
|
||||
"geo_radius": gorm.Expr("EXCLUDED.geo_radius"),
|
||||
"created_by": gorm.Expr("EXCLUDED.created_by"),
|
||||
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||
}),
|
||||
}).
|
||||
Create(code).Error
|
||||
@@ -764,6 +794,19 @@ func (r *trainingRepository) GetSignCodeByToken(ctx context.Context, tenantID ui
|
||||
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).
|
||||
func (r *trainingRepository) UpsertSignRecord(ctx context.Context, record *types.TrainingSignRecord) error {
|
||||
return r.db.WithContext(ctx).
|
||||
@@ -782,6 +825,18 @@ func (r *trainingRepository) GetSignRecord(ctx context.Context, tenantID uint64,
|
||||
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 (复核入口)。
|
||||
func (r *trainingRepository) GetSignRecordByID(ctx context.Context, tenantID uint64, id string) (*types.TrainingSignRecord, error) {
|
||||
var rec types.TrainingSignRecord
|
||||
|
||||
@@ -44,6 +44,10 @@ type customAgentService struct {
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
agentShareRepo interfaces.AgentShareRepository
|
||||
// modelService is optional (nil in some unit tests) and only used by
|
||||
// the create-time fallback that fills an empty Config.ModelID with the
|
||||
// tenant-visible default chat model (out-of-the-box experience).
|
||||
modelService interfaces.ModelService
|
||||
}
|
||||
|
||||
// NewCustomAgentService creates a new custom agent service
|
||||
@@ -56,6 +60,7 @@ func NewCustomAgentService(
|
||||
tagRepo interfaces.KnowledgeTagRepository,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
agentShareRepo interfaces.AgentShareRepository,
|
||||
modelService interfaces.ModelService,
|
||||
) interfaces.CustomAgentService {
|
||||
return &customAgentService{
|
||||
repo: repo,
|
||||
@@ -66,6 +71,7 @@ func NewCustomAgentService(
|
||||
tagRepo: tagRepo,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
agentShareRepo: agentShareRepo,
|
||||
modelService: modelService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +116,24 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default
|
||||
// 优先,否则该类型第一个 active)。fail-open:解析不到保持为空,
|
||||
// 运行时的 "chat model is not configured" 报错行为与现状一致。
|
||||
// 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 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 {
|
||||
logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
|
||||
agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
|
||||
|
||||
|
||||
@@ -141,6 +141,22 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
|
||||
}
|
||||
kb.EnsureDefaults()
|
||||
applyTenantDefaultStorageProvider(ctx, kb)
|
||||
// 开箱即用兜底:对话/向量化模型为空时自动落到系统默认(内置
|
||||
// is_default 优先,否则该类型第一个 active)。fail-open:解析不到
|
||||
// 保持为空,与用户显式不选的行为一致(空 embedding + 向量索引开启
|
||||
// 时的检索回退由查询侧既有逻辑处理)。
|
||||
if kb.SummaryModelID == "" || kb.EmbeddingModelID == "" {
|
||||
if models, listErr := s.modelService.ListModels(ctx); listErr == nil {
|
||||
if kb.SummaryModelID == "" {
|
||||
kb.SummaryModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
|
||||
}
|
||||
if kb.EmbeddingModelID == "" {
|
||||
kb.EmbeddingModelID = PickDefaultModelID(models, types.ModelTypeEmbedding)
|
||||
}
|
||||
} else {
|
||||
logger.Warnf(ctx, "[kb.create] default model fallback lookup failed: %v", listErr)
|
||||
}
|
||||
}
|
||||
if err := s.applyAndValidateStorageBackend(ctx, kb); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
@@ -10,16 +13,29 @@ import (
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。
|
||||
// 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色,
|
||||
// 部门/岗位/姓名只维护一份。
|
||||
type orgCenterService struct {
|
||||
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.
|
||||
func NewOrgCenterService(repo interfaces.OrgCenterRepository) interfaces.OrgCenterService {
|
||||
return &orgCenterService{repo: repo}
|
||||
func NewOrgCenterService(
|
||||
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 ""
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) {
|
||||
if employee.ID == "" {
|
||||
@@ -199,6 +275,135 @@ func (s *orgCenterService) ListTenantUsers(ctx context.Context, tenantID uint64)
|
||||
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) {
|
||||
repo := newFakeOrgRepo()
|
||||
svc := NewOrgCenterService(repo)
|
||||
svc := NewOrgCenterService(repo, nil, nil, nil)
|
||||
employees := []*types.OrgEmployee{
|
||||
{UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号
|
||||
{UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号
|
||||
@@ -76,7 +76,7 @@ func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
|
||||
|
||||
func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) {
|
||||
repo := newFakeOrgRepo()
|
||||
svc := NewOrgCenterService(repo)
|
||||
svc := NewOrgCenterService(repo, nil, nil, nil)
|
||||
// u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。
|
||||
employees := []*types.OrgEmployee{
|
||||
{UserID: "u-qu", DeptID: "d1"},
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 新工作空间开箱即用初始化(tenant bootstrap)
|
||||
//
|
||||
// 目标:新用户注册/新建空间后,无需手动配置任何模型即可直接使用:
|
||||
// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先);
|
||||
// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型;
|
||||
// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化);
|
||||
// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认;
|
||||
// 5. 确保企业培训「课件/题库」两个系统默认知识库(CASDOOR/OIDC 自动注册
|
||||
// 用户进「知识库」页默认可见,与培训域共用同一对库)。
|
||||
//
|
||||
// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程;
|
||||
// 且整体幂等——租户下已存在同名入门库时直接跳过。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const (
|
||||
// BootstrapKBName 开箱默认知识库名;幂等检查按此名匹配。
|
||||
BootstrapKBName = "新手入门"
|
||||
|
||||
bootstrapWelcomeFileName = "欢迎使用指南.md"
|
||||
)
|
||||
|
||||
// bootstrapWelcomeDocContent 预置欢迎文档内容。走标准文档解析管道,
|
||||
// 处理完成后用户即可在「新手入门」库上直接问答验证开箱效果。
|
||||
const bootstrapWelcomeDocContent = `# 欢迎使用 Academy
|
||||
|
||||
这是一份由系统自动创建的入门知识库,已经为你配置好默认的对话与向量化模型——
|
||||
现在你可以直接开始提问了。
|
||||
|
||||
## 你现在就可以做什么
|
||||
|
||||
- **知识库问答**:进入任意知识库,右侧对话面板直接提问。本库已内置这份入门指南,
|
||||
可以试试问它:"这个平台能做什么?"
|
||||
- **智能体对话**:打开对话页面即可与 Academy 助手聊天,助手默认使用系统配置好的对话模型。
|
||||
|
||||
## 接下来你可能想做的事
|
||||
|
||||
1. **创建自己的知识库**:左侧知识库 → 新建知识库。系统会自动为你预填默认模型,
|
||||
上传文档(支持 Markdown、Word、PDF、Excel 等)后即可对文档内容提问。
|
||||
2. **创建智能体**:智能体页面 → 新建。主模型同样自动预填;你还可以为智能体单独配置
|
||||
重排、视觉(图片理解)、语音(ASR)等模型。
|
||||
3. **邀请团队成员**:右上角头像 → 设置 → 成员管理 → 邀请成员。支持单个邀请、
|
||||
生成共享链接,以及按 Excel 模板批量导入成员。
|
||||
4. **管理模型**:设置 → 模型管理。系统内置的默认模型已开箱可用;如需接入
|
||||
自己的模型(OpenAI 兼容 API、Ollama 本地模型、各云厂商),在「添加模型」中配置即可。
|
||||
|
||||
## 小提示
|
||||
|
||||
- 带锁图标的模型是系统内置模型,所有空间共享,可直接使用。
|
||||
- 新建知识库/智能体时,模型字段已自动填好默认值,不需要手动选择;当然你随时可以更换。
|
||||
|
||||
祝使用愉快!
|
||||
`
|
||||
|
||||
// NewTenantBootstrapService wires the bootstrap service. All dependencies are
|
||||
// optional at the DI level but each seeding step degrades gracefully when its
|
||||
// service misbehaves (fail-open, see SeedTenantDefaults).
|
||||
func NewTenantBootstrapService(
|
||||
modelService interfaces.ModelService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kgService interfaces.KnowledgeService,
|
||||
tenantService interfaces.TenantService,
|
||||
) interfaces.TenantBootstrapService {
|
||||
return &tenantBootstrapService{
|
||||
modelService: modelService,
|
||||
kbService: kbService,
|
||||
kgService: kgService,
|
||||
tenantService: tenantService,
|
||||
}
|
||||
}
|
||||
|
||||
type tenantBootstrapService struct {
|
||||
modelService interfaces.ModelService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kgService interfaces.KnowledgeService
|
||||
tenantService interfaces.TenantService
|
||||
// ensureMu 串行化惰性自愈的补建段(见 EnsureTenantDefaultKnowledgeBases)。
|
||||
ensureMu sync.Mutex
|
||||
}
|
||||
|
||||
// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the
|
||||
// interface doc for the contract; every step logs and moves on.
|
||||
func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) {
|
||||
// 整体兜底:seed 属于附加体验,任何 panic(如上游依赖 nil)都不能
|
||||
// 波及注册/建租户主流程。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Errorf(ctx, "tenant bootstrap: recovered from panic: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
if tenant == nil || tenant.ID == 0 {
|
||||
return
|
||||
}
|
||||
// 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。000160 起
|
||||
// 租户序列已避开 10000(见 migration 000160_tenant_seq_reserve_builtin_host),
|
||||
// 新环境不会再有真实空间拿到该 id;存量环境若首空间已占住 10000(引导因此
|
||||
// 被跳过,一个默认库都没有),其默认库由 EnsureTenantDefaultKnowledgeBases
|
||||
// 惰性自愈补齐——该路径不带本豁免。
|
||||
if tenant.ID == types.DefaultBuiltinModelTenantID {
|
||||
return
|
||||
}
|
||||
|
||||
// 构造服务级 ctx:显式指定执行租户与租户信息(CreateKnowledgeFromFile
|
||||
// 依赖 TenantInfo),并归因创建人(synthetic API-key 用户跳过,同 KB
|
||||
// 服务的 CreatorID 语义)。必须先于所有服务调用——挂钩处的调用方 ctx
|
||||
// 还停留在调用者的"当前空间",不是刚创建的新空间。
|
||||
seedCtx := types.WithExecutionTenant(ctx, tenant.ID)
|
||||
seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant)
|
||||
if ownerUserID != "" && !types.IsSyntheticUserID(ownerUserID) {
|
||||
seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, ownerUserID)
|
||||
}
|
||||
|
||||
// 幂等:已有同名入门库的工作空间视为已初始化。
|
||||
kbs, err := s.kbService.ListKnowledgeBasesByTenantID(seedCtx, tenant.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 企业培训(课件)/(题库)系统默认库:按 Source 标记独立幂等确保(与培训域
|
||||
// ensureTrainingKnowledgeBases 同源),入门库已初始化的空间同样补齐 ——
|
||||
// CASDOOR/OIDC 自动注册的用户进「知识库」页即可见两个培训默认库。
|
||||
s.ensureTrainingKnowledgeBases(seedCtx, tenant.ID, kbs)
|
||||
|
||||
for _, kb := range kbs {
|
||||
if kb != nil && kb.Name == BootstrapKBName {
|
||||
logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 解析系统默认模型(内置 is_default 优先,否则该类型第一个 active)。
|
||||
models, err := s.modelService.ListModels(seedCtx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "tenant bootstrap: list models failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
||||
return
|
||||
}
|
||||
chatID := PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
|
||||
embedID := PickDefaultModelID(models, types.ModelTypeEmbedding)
|
||||
rerankID := PickDefaultModelID(models, types.ModelTypeRerank)
|
||||
|
||||
// 1) 默认知识库 + 欢迎文档(创建时引导与存量空间自愈共用同一实现)。
|
||||
// 模型解析不到就留空——行为与用户手动不选一致。
|
||||
if err := s.seedStarterKB(seedCtx, chatID, embedID); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 2) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
|
||||
if rerankID != "" {
|
||||
if tenant.RetrievalConfig == nil {
|
||||
tenant.RetrievalConfig = &types.RetrievalConfig{}
|
||||
}
|
||||
if tenant.RetrievalConfig.RerankModelID == "" {
|
||||
tenant.RetrievalConfig.RerankModelID = rerankID
|
||||
if _, err := s.tenantService.UpdateTenant(ctx, tenant); err != nil {
|
||||
logger.Warnf(ctx, "tenant bootstrap: set tenant rerank model failed: tenant=%d err=%v",
|
||||
tenant.ID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "tenant bootstrap: tenant rerank model set: tenant=%d model=%s",
|
||||
tenant.ID, rerankID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
// create-time fallbacks (KB / agent) so every path resolves defaults the
|
||||
// same way.
|
||||
func PickDefaultModelID(models []*types.Model, modelType types.ModelType) string {
|
||||
first := ""
|
||||
for _, m := range models {
|
||||
if m == nil || m.Type != modelType || strings.TrimSpace(m.ID) == "" {
|
||||
continue
|
||||
}
|
||||
if m.Status != "" && m.Status != types.ModelStatusActive {
|
||||
continue
|
||||
}
|
||||
if m.IsDefault {
|
||||
return m.ID
|
||||
}
|
||||
if first == "" {
|
||||
first = m.ID
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
// buildInMemoryFileHeader constructs a real *multipart.FileHeader for in-memory
|
||||
// content so service paths that expect an uploaded file (CreateKnowledgeFromFile)
|
||||
// can be reused without an HTTP round-trip. FileHeader's Open() reads unexported
|
||||
// content captured by multipart form parsing, so the only reliable construction
|
||||
// is a synthetic multipart round-trip in memory.
|
||||
func buildInMemoryFileHeader(name, content string) (*multipart.FileHeader, error) {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return nil, errors.New("file name is required")
|
||||
}
|
||||
body := &bytes.Buffer{}
|
||||
mw := multipart.NewWriter(body)
|
||||
fw, err := mw.CreateFormFile("file", name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.Copy(fw, strings.NewReader(content)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
form, err := multipart.NewReader(body, mw.Boundary()).ReadForm(int64(body.Len()) + 1<<20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fhs := form.File["file"]
|
||||
if len(fhs) == 0 {
|
||||
return nil, errors.New("multipart form contains no file part")
|
||||
}
|
||||
return fhs[0], nil
|
||||
}
|
||||
@@ -79,6 +79,7 @@ type tenantMemberService struct {
|
||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||
userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers
|
||||
tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal
|
||||
org interfaces.OrgCenterService // optional; 成员加入时自动入册组织架构(见 ensureOrgRoster)
|
||||
}
|
||||
|
||||
// NewTenantMemberService constructs the service. Wired up via the DI
|
||||
@@ -100,12 +101,28 @@ func NewTenantMemberService(
|
||||
audit interfaces.AuditLogService,
|
||||
userRepo interfaces.UserRepository,
|
||||
tokenRepo interfaces.AuthTokenRepository,
|
||||
org interfaces.OrgCenterService,
|
||||
) interfaces.TenantMemberService {
|
||||
return &tenantMemberService{
|
||||
repo: repo,
|
||||
audit: audit,
|
||||
userRepo: userRepo,
|
||||
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
|
||||
}
|
||||
if existing != nil {
|
||||
// 已是成员:仍补一次入册(存量成员档案缺失时的自愈口)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return nil, ErrMembershipAlreadyExists
|
||||
}
|
||||
member := &types.TenantMember{
|
||||
@@ -201,6 +220,8 @@ func (s *tenantMemberService) AddMember(
|
||||
TargetUserID: userID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
})
|
||||
// 成员关系落库后自动入册组织架构(新增成员自动添加到名册并匹配部门)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return member, nil
|
||||
}
|
||||
|
||||
@@ -218,6 +239,7 @@ func (s *tenantMemberService) EnsureOwner(
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return existing, nil
|
||||
}
|
||||
member := &types.TenantMember{
|
||||
@@ -239,12 +261,15 @@ func (s *tenantMemberService) EnsureOwner(
|
||||
logger.Infof(ctx,
|
||||
"EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)",
|
||||
userID, tenantID, winner.Role)
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return winner, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID)
|
||||
// 注册建空间的 Owner 同样自动入册(个人空间名册含创建者本人)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return member, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/integrations/casdoor"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 同步CASDOOR成员(设置 → 成员管理,000156):
|
||||
// 经 Casdoor 管理 API 拉全量用户目录 → 部门落 org_depts → 账号 upsert
|
||||
// (工号优先匹配,未注册自动开户,与成员批量导入同模式) → viewer 加入空间。
|
||||
// 单向增量幂等:不删除、不停用、不改已有成员角色;Casdoor 无部门数据时
|
||||
// 自动降级为纯成员同步(部门列留空)。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// casdoorMemberUsernameMax 与 RegisterRequest 的 max=50 一致,
|
||||
// Casdoor 工号超长视为脏数据整条跳过。
|
||||
const casdoorMemberUsernameMax = 50
|
||||
|
||||
// casdoorMemberSyncService 实现 interfaces.CasdoorMemberSyncService。
|
||||
type casdoorMemberSyncService struct {
|
||||
client *casdoor.Client
|
||||
users interfaces.UserService
|
||||
members interfaces.TenantMemberService
|
||||
org interfaces.OrgCenterService
|
||||
// fallbackDomain 与 OIDC 登录/成员导入同源的占位邮箱兜底域(casdoor.local)。
|
||||
fallbackDomain string
|
||||
}
|
||||
|
||||
// NewCasdoorMemberSyncService 装配同步服务。OIDC 段缺失或未开启管理 API
|
||||
// 开关时 client 为 nil,SyncMembers 返回可操作的配置提示(而不是 panic)。
|
||||
func NewCasdoorMemberSyncService(
|
||||
cfg *config.Config,
|
||||
users interfaces.UserService,
|
||||
members interfaces.TenantMemberService,
|
||||
org interfaces.OrgCenterService,
|
||||
) interfaces.CasdoorMemberSyncService {
|
||||
svc := &casdoorMemberSyncService{
|
||||
users: users,
|
||||
members: members,
|
||||
org: org,
|
||||
}
|
||||
if cfg != nil && cfg.OIDCAuth != nil {
|
||||
if cfg.OIDCAuth.AdminAPIEnabled {
|
||||
svc.client = casdoor.NewClientFromOIDC(cfg.OIDCAuth)
|
||||
}
|
||||
svc.fallbackDomain = cfg.OIDCAuth.EmailFallbackDomain
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// SyncMembers 执行一次全量同步,返回汇总结果。
|
||||
func (s *casdoorMemberSyncService) SyncMembers(
|
||||
ctx context.Context, tenantID uint64, operatorID string,
|
||||
) (*types.CasdoorSyncResult, error) {
|
||||
if s.client == nil || !s.client.Enabled() {
|
||||
return nil, errors.New("Casdoor 同步未启用:需设置 OIDC_AUTH_ADMIN_API_ENABLE=true 并配置管理 API(见 .env.example F3 段)")
|
||||
}
|
||||
|
||||
rawUsers, deptSource, err := s.client.ListUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, s.wrapClientError(err)
|
||||
}
|
||||
result := &types.CasdoorSyncResult{
|
||||
Total: len(rawUsers),
|
||||
DeptSource: deptSource,
|
||||
}
|
||||
|
||||
// 部门同步只在 Casdoor 真有部门数据时执行(DeptSource 非空),
|
||||
// 避免把空名称部门写进组织架构。
|
||||
if deptSource != "" {
|
||||
s.syncDepts(ctx, tenantID, rawUsers, result)
|
||||
}
|
||||
|
||||
// 邀请归因:合成主体(API key 等)不作为 invited_by,与 AddMember 同规则。
|
||||
var invitedBy *string
|
||||
if operatorID != "" && !types.IsSyntheticUserID(operatorID) {
|
||||
invitedBy = &operatorID
|
||||
}
|
||||
|
||||
seen := map[string]bool{} // 工号/邮箱批内去重(小写)
|
||||
for _, u := range rawUsers {
|
||||
if skip := casdoorSkipReason(u); skip != "" {
|
||||
s.appendSkip(result, u, skip)
|
||||
continue
|
||||
}
|
||||
employeeNo := strings.TrimSpace(u.Name)
|
||||
email := s.resolveEmail(employeeNo, u.Email)
|
||||
|
||||
// 批内去重(校验通过后才登记,坏行不占身份键)。
|
||||
idKeys := []string{email, strings.ToLower(employeeNo)}
|
||||
duplicated := false
|
||||
for _, key := range idKeys {
|
||||
if seen[key] {
|
||||
duplicated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if duplicated {
|
||||
s.appendSkip(result, u, "目录内重复:工号或邮箱与前面的用户相同")
|
||||
continue
|
||||
}
|
||||
|
||||
user, created, err := s.upsertUser(ctx, employeeNo, email, u)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "casdoor sync upsert user failed: employee_no=%s err=%v",
|
||||
employeeNo, err)
|
||||
s.appendSkip(result, u, "账号处理失败:"+err.Error())
|
||||
continue
|
||||
}
|
||||
for _, key := range idKeys {
|
||||
seen[key] = true
|
||||
}
|
||||
|
||||
if _, err := s.members.AddMember(ctx, user.ID, tenantID, types.TenantRoleViewer, invitedBy); err != nil {
|
||||
if errors.Is(err, ErrMembershipAlreadyExists) {
|
||||
result.MembersExist++
|
||||
continue
|
||||
}
|
||||
logger.Errorf(ctx, "casdoor sync add member failed: user=%s tenant=%d err=%v",
|
||||
user.ID, tenantID, err)
|
||||
s.appendSkip(result, u, "加入空间失败:"+err.Error())
|
||||
continue
|
||||
}
|
||||
result.MembersAdded++
|
||||
if created {
|
||||
result.UsersCreated++
|
||||
}
|
||||
|
||||
// 无归属空间的账号(含本次新建)收编为该空间默认空间,首次登录
|
||||
// 即落在正确的工作区(与成员批量导入 auto-accept 路径一致)。
|
||||
// 失败只告警:成员关系已写入,登录路径的成员检查会兜底。
|
||||
if user.TenantID == 0 {
|
||||
user.TenantID = tenantID
|
||||
user.UpdatedAt = time.Now()
|
||||
if err := s.users.UpdateUser(ctx, user); err != nil {
|
||||
logger.Warnf(ctx, "casdoor sync: member added but default tenant update failed: user=%s tenant=%d err=%v",
|
||||
user.ID, tenantID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// casdoorSkipReason 返回跳过原因;空串表示该用户应正常处理。
|
||||
func casdoorSkipReason(u *casdoor.User) string {
|
||||
switch {
|
||||
case u == nil || strings.TrimSpace(u.Name) == "":
|
||||
return "缺少工号(Casdoor name 为空)"
|
||||
case u.IsDeleted:
|
||||
return "Casdoor 侧已删除"
|
||||
case u.IsForbidden:
|
||||
return "Casdoor 侧已停用"
|
||||
case len(strings.TrimSpace(u.Name)) > casdoorMemberUsernameMax:
|
||||
return "工号过长(最多 50 字符)"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// syncDepts 把目录中的唯一部门(编号,名称)对齐进组织架构:
|
||||
// 编号命中 → 复用;名称命中(编号为空或不同) → 回填编号;都没有 → 新建。
|
||||
// Casdoor 手工建过的部门不会因同步而重名重复。
|
||||
func (s *casdoorMemberSyncService) syncDepts(
|
||||
ctx context.Context, tenantID uint64, users []*casdoor.User, result *types.CasdoorSyncResult,
|
||||
) {
|
||||
depts, err := s.org.ListDepts(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "casdoor sync list depts failed (dept sync skipped): tenant=%d err=%v", tenantID, err)
|
||||
return
|
||||
}
|
||||
byCode := map[string]*types.OrgDept{} // 小写编号 → 部门
|
||||
byName := map[string]*types.OrgDept{} // 小写名称 → 部门
|
||||
for _, d := range depts {
|
||||
if d == nil {
|
||||
continue
|
||||
}
|
||||
if code := strings.ToLower(strings.TrimSpace(d.Code)); code != "" {
|
||||
byCode[code] = d
|
||||
}
|
||||
if name := strings.ToLower(strings.TrimSpace(d.Name)); name != "" {
|
||||
if _, exists := byName[name]; !exists {
|
||||
byName[name] = d // 首见优先,与 ListDepts 的 sort/created_at 序一致
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 目录内去重:同一部门(编号/名称)只处理一次。
|
||||
type deptKey struct{ code, name string }
|
||||
unique := map[string]deptKey{}
|
||||
order := []string{} // 保持目录出现顺序,结果可预期
|
||||
for _, u := range users {
|
||||
if u == nil || strings.TrimSpace(u.DeptName) == "" {
|
||||
continue
|
||||
}
|
||||
id := strings.ToLower(strings.TrimSpace(u.DeptCode)) + "|" +
|
||||
strings.ToLower(strings.TrimSpace(u.DeptName))
|
||||
if _, exists := unique[id]; !exists {
|
||||
unique[id] = deptKey{code: strings.TrimSpace(u.DeptCode), name: strings.TrimSpace(u.DeptName)}
|
||||
order = append(order, id)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range order {
|
||||
key := unique[id]
|
||||
if key.code != "" {
|
||||
if _, ok := byCode[strings.ToLower(key.code)]; ok {
|
||||
continue // 编号已存在,复用
|
||||
}
|
||||
}
|
||||
existing, ok := byName[strings.ToLower(key.name)]
|
||||
if ok {
|
||||
// 名称命中但缺编号/编号不同 → 回填编号(手工建过的老部门)。
|
||||
if key.code != "" && strings.TrimSpace(existing.Code) == "" {
|
||||
existing.Code = key.code
|
||||
existing.UpdatedAt = time.Now()
|
||||
if _, err := s.org.SaveDept(ctx, tenantID, existing); err != nil {
|
||||
logger.Warnf(ctx, "casdoor sync backfill dept code failed: dept=%s err=%v",
|
||||
existing.ID, err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
dept, err := s.org.SaveDept(ctx, tenantID, &types.OrgDept{
|
||||
Name: key.name,
|
||||
Code: key.code,
|
||||
})
|
||||
if err != nil {
|
||||
// 唯一索引竞态等:单部门失败不阻断,下轮同步可补。
|
||||
logger.Warnf(ctx, "casdoor sync create dept failed: name=%s code=%s err=%v",
|
||||
key.name, key.code, err)
|
||||
continue
|
||||
}
|
||||
result.DeptsCreated++
|
||||
if key.code != "" {
|
||||
byCode[strings.ToLower(key.code)] = dept
|
||||
}
|
||||
byName[strings.ToLower(key.name)] = dept
|
||||
}
|
||||
}
|
||||
|
||||
// upsertUser 工号优先、邮箱兜底匹配已有账号;未命中自动开户
|
||||
// (随机密码、tenantless、OidcOnlyLogin——与 OIDC 首登开户同模式,首次
|
||||
// Casdoor 登录时按工号收编,不会重复开户)。成功后回写部门字段。
|
||||
// 返回 (用户, 是否本次新建, 错误)。
|
||||
func (s *casdoorMemberSyncService) upsertUser(
|
||||
ctx context.Context, employeeNo, email string, u *casdoor.User,
|
||||
) (*types.User, bool, error) {
|
||||
user, err := s.users.GetUserByUsername(ctx, employeeNo)
|
||||
if err != nil && !errors.Is(err, ErrUserNotFound) {
|
||||
return nil, false, fmt.Errorf("按工号查询失败: %w", err)
|
||||
}
|
||||
if user == nil && email != "" {
|
||||
user, err = s.users.GetUserByEmail(ctx, email)
|
||||
if err != nil && !errors.Is(err, ErrUserNotFound) {
|
||||
return nil, false, fmt.Errorf("按邮箱查询失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
created, err := s.createUser(ctx, employeeNo, email, u)
|
||||
return created, true, err
|
||||
}
|
||||
|
||||
// 已有账号:补姓名、回写部门(以 Casdoor 为源),失败仅告警不阻断成员加入。
|
||||
if user.DisplayName == "" && strings.TrimSpace(u.DisplayName) != "" {
|
||||
user.DisplayName = strings.TrimSpace(u.DisplayName)
|
||||
}
|
||||
s.applyDept(user, u)
|
||||
user.UpdatedAt = time.Now()
|
||||
if err := s.users.UpdateUser(ctx, user); err != nil {
|
||||
logger.Warnf(ctx, "casdoor sync user refresh failed: user=%s err=%v", user.ID, err)
|
||||
}
|
||||
return user, false, nil
|
||||
}
|
||||
|
||||
// createUser 自动开户(与成员批量导入 createImportUser 同模式)。
|
||||
func (s *casdoorMemberSyncService) createUser(
|
||||
ctx context.Context, employeeNo, email string, u *casdoor.User,
|
||||
) (*types.User, error) {
|
||||
password, err := generateRandomString(32)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("生成初始密码失败: %w", err)
|
||||
}
|
||||
user, err := s.users.Register(ctx, &types.RegisterRequest{
|
||||
Username: employeeNo,
|
||||
Email: email,
|
||||
Password: password,
|
||||
TenantProvisioning: types.TenantProvisioningTenantless,
|
||||
})
|
||||
if err != nil {
|
||||
// 唯一键竞态(并发注册/导入占用工号或邮箱):按工号重查兜底。
|
||||
if errors.Is(err, ErrUserEmailExists) || errors.Is(err, ErrUserUsernameExists) {
|
||||
if existing, lookupErr := s.users.GetUserByUsername(ctx, employeeNo); lookupErr == nil && existing != nil {
|
||||
return existing, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if trimmed := strings.TrimSpace(u.DisplayName); trimmed != "" {
|
||||
user.DisplayName = trimmed
|
||||
}
|
||||
oidcOnly := true
|
||||
if user.Preferences.OidcOnlyLogin == nil {
|
||||
user.Preferences.OidcOnlyLogin = &oidcOnly
|
||||
}
|
||||
s.applyDept(user, u)
|
||||
user.UpdatedAt = time.Now()
|
||||
if err := s.users.UpdateUser(ctx, user); err != nil {
|
||||
return nil, fmt.Errorf("初始化账号资料失败: %w", err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// applyDept 把 Casdoor 部门编号/名称写上用户(同步态,每次同步覆盖)。
|
||||
func (s *casdoorMemberSyncService) applyDept(user *types.User, u *casdoor.User) {
|
||||
user.DeptCode = strings.TrimSpace(u.DeptCode)
|
||||
user.DeptName = strings.TrimSpace(u.DeptName)
|
||||
}
|
||||
|
||||
// resolveEmail 归一邮箱:Casdoor 有真实邮箱用之;缺失时按工号合成占位地址
|
||||
// (与 OIDC 登录/成员导入同规则;合成邮箱是永久账号键)。
|
||||
func (s *casdoorMemberSyncService) resolveEmail(employeeNo, raw string) string {
|
||||
email := strings.ToLower(strings.TrimSpace(raw))
|
||||
if email == "" && s.fallbackDomain != "" {
|
||||
email = synthesizeOIDCEmail(employeeNo, employeeNo, s.fallbackDomain)
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
// appendSkip 记录一条跳过(工号+邮箱+原因)。
|
||||
func (s *casdoorMemberSyncService) appendSkip(result *types.CasdoorSyncResult, u *casdoor.User, reason string) {
|
||||
name := ""
|
||||
email := ""
|
||||
if u != nil {
|
||||
name = strings.TrimSpace(u.Name)
|
||||
email = strings.TrimSpace(u.Email)
|
||||
}
|
||||
result.Skipped = append(result.Skipped, types.CasdoorSyncSkip{
|
||||
Name: name,
|
||||
Email: email,
|
||||
Reason: reason,
|
||||
})
|
||||
}
|
||||
|
||||
// wrapClientError 把 Casdoor 客户端错误翻译成可操作的提示文案。
|
||||
func (s *casdoorMemberSyncService) wrapClientError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, casdoor.ErrGrantNotSupported):
|
||||
if s.fallbackAdminConfigured() {
|
||||
return errors.New("Casdoor 应用未开启 password 授权:请在 Casdoor 管理台 → 应用编辑 → Token 授权类型(grantTypes)勾选 Password 后重试;或改配 client_credentials 模式")
|
||||
}
|
||||
return errors.New("Casdoor 应用未开启 Client Credentials 授权:请勾选该授权,或改配服务账号密码模式(OIDC_AUTH_ADMIN_USERNAME/PASSWORD)后重试")
|
||||
case errors.Is(err, casdoor.ErrAdminDenied):
|
||||
return errors.New("Casdoor 管理 API 访问被拒:请确认凭据所属账号/应用具备目标组织的管理权限")
|
||||
}
|
||||
return fmt.Errorf("拉取 Casdoor 用户失败: %w", err)
|
||||
}
|
||||
|
||||
// fallbackAdminConfigured 是否已配置服务账号密码模式。
|
||||
func (s *casdoorMemberSyncService) fallbackAdminConfigured() bool {
|
||||
return s.client != nil && s.client.PasswordMode()
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/config"
|
||||
"academy/internal/integrations/casdoor"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 同步CASDOOR成员(000156)单测:
|
||||
// httptest 假 Casdoor 管理 API + fake 用户/成员/组织依赖,覆盖
|
||||
// 自动开户、工号优先匹配、已有成员幂等、停用用户跳过、无部门数据降级、
|
||||
// 部门编号回填与新建。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// fakeCasdoorServer 起 Casdoor 管理 API 假端点(token + get-users)。
|
||||
func fakeCasdoorServer(t *testing.T, users []map[string]interface{}, wrap ...bool) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/login/oauth/access_token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
// 两种 grant 都支持:client_credentials(client_id 必填)与
|
||||
// password(用户名必须是 svc-academy-sync 且密码非空)。
|
||||
grant := r.Form.Get("grant_type")
|
||||
switch grant {
|
||||
case "client_credentials":
|
||||
if r.Form.Get("client_id") == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"unsupported_grant_type","error_description":"grant_type: client_credentials is not supported in this application"}`))
|
||||
return
|
||||
}
|
||||
case "password":
|
||||
if r.Form.Get("username") != "svc-academy-sync" || r.Form.Get("password") == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant","error_description":"the user does not exist"}`))
|
||||
return
|
||||
}
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"unsupported_grant_type"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"access_token":"tok-1","token_type":"Bearer","expires_in":3600}`))
|
||||
})
|
||||
mux.HandleFunc("/api/get-users", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Header.Get("Authorization") != "Bearer tok-1" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"status":"error","msg":"access denied"}`))
|
||||
return
|
||||
}
|
||||
if len(wrap) > 0 && wrap[0] {
|
||||
// 信封形态: {"status":"ok","data":[...]}
|
||||
_, _ = w.Write([]byte(`{"status":"ok","msg":"","data":`))
|
||||
_ = json.NewEncoder(w).Encode(users)
|
||||
_, _ = w.Write([]byte(`}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(users)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// casdoorUser 构造一条目录记录(name=工号必填,其余选填)。
|
||||
func casdoorUser(name, displayName, email string, extra map[string]interface{}) map[string]interface{} {
|
||||
u := map[string]interface{}{
|
||||
"owner": "built-in",
|
||||
"name": name,
|
||||
"displayName": displayName,
|
||||
"isAdmin": false,
|
||||
"isForbidden": false,
|
||||
"isDeleted": false,
|
||||
}
|
||||
if email != "" {
|
||||
u["email"] = email
|
||||
}
|
||||
for k, v := range extra {
|
||||
u[k] = v
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// fakeSyncUsers 平台账号内存实现(工号/邮箱双键唯一,模拟唯一键竞态语义)。
|
||||
type fakeSyncUsers struct {
|
||||
interfaces.UserService
|
||||
byEmail map[string]*types.User
|
||||
byUsername map[string]*types.User
|
||||
created []string // 新开户工号
|
||||
updated []string // UpdateUser 过的用户 ID
|
||||
idSeq int
|
||||
}
|
||||
|
||||
func newFakeSyncUsers(existing ...*types.User) *fakeSyncUsers {
|
||||
f := &fakeSyncUsers{
|
||||
byEmail: map[string]*types.User{},
|
||||
byUsername: map[string]*types.User{},
|
||||
}
|
||||
for _, u := range existing {
|
||||
f.byEmail[u.Email] = u
|
||||
f.byUsername[u.Username] = u
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeSyncUsers) Register(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
if _, ok := f.byEmail[req.Email]; ok {
|
||||
return nil, ErrUserEmailExists
|
||||
}
|
||||
if _, ok := f.byUsername[req.Username]; ok {
|
||||
return nil, ErrUserUsernameExists
|
||||
}
|
||||
f.idSeq++
|
||||
u := &types.User{ID: fmt.Sprintf("u-%d", f.idSeq), Username: req.Username, Email: req.Email}
|
||||
f.byEmail[u.Email] = u
|
||||
f.byUsername[u.Username] = u
|
||||
f.created = append(f.created, req.Username)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (f *fakeSyncUsers) GetUserByEmail(_ context.Context, email string) (*types.User, error) {
|
||||
if u, ok := f.byEmail[email]; ok {
|
||||
return u, nil
|
||||
}
|
||||
return nil, repository.ErrUserNotFound
|
||||
}
|
||||
|
||||
func (f *fakeSyncUsers) GetUserByUsername(_ context.Context, username string) (*types.User, error) {
|
||||
if u, ok := f.byUsername[username]; ok {
|
||||
return u, nil
|
||||
}
|
||||
return nil, repository.ErrUserNotFound
|
||||
}
|
||||
|
||||
func (f *fakeSyncUsers) UpdateUser(_ context.Context, u *types.User) error {
|
||||
f.updated = append(f.updated, u.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeSyncMembers 空间成员内存实现(同 (user,tenant) 二次加入返回已存在)。
|
||||
type fakeSyncMembers struct {
|
||||
interfaces.TenantMemberService
|
||||
added map[string]types.TenantRole // user_id → role
|
||||
}
|
||||
|
||||
func newFakeSyncMembers() *fakeSyncMembers {
|
||||
return &fakeSyncMembers{added: map[string]types.TenantRole{}}
|
||||
}
|
||||
|
||||
func (f *fakeSyncMembers) AddMember(
|
||||
_ context.Context, userID string, _ uint64, role types.TenantRole, _ *string,
|
||||
) (*types.TenantMember, error) {
|
||||
if _, ok := f.added[userID]; ok {
|
||||
return nil, ErrMembershipAlreadyExists
|
||||
}
|
||||
f.added[userID] = role
|
||||
return &types.TenantMember{UserID: userID, TenantID: 7, Role: role}, nil
|
||||
}
|
||||
|
||||
// fakeSyncOrgRepo 组织架构部门内存实现(供真实 OrgCenterService 使用)。
|
||||
type fakeSyncOrgRepo struct {
|
||||
interfaces.OrgCenterRepository
|
||||
depts []*types.OrgDept
|
||||
idSeq int
|
||||
created []string
|
||||
codeSetBy map[string]string // dept id → 回填的编号
|
||||
}
|
||||
|
||||
func (f *fakeSyncOrgRepo) ListDepts(context.Context, uint64) ([]*types.OrgDept, error) {
|
||||
return f.depts, nil
|
||||
}
|
||||
|
||||
func (f *fakeSyncOrgRepo) CreateDept(_ context.Context, dept *types.OrgDept) error {
|
||||
f.idSeq++
|
||||
dept.ID = fmt.Sprintf("d-%d", f.idSeq)
|
||||
f.created = append(f.created, dept.Name)
|
||||
f.depts = append(f.depts, dept)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSyncOrgRepo) UpdateDept(_ context.Context, dept *types.OrgDept) error {
|
||||
for _, d := range f.depts {
|
||||
if d.ID == dept.ID {
|
||||
d.Code = dept.Code
|
||||
f.codeSetBy[d.ID] = dept.Code
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSyncService 组装被测服务。
|
||||
func newSyncService(
|
||||
t *testing.T, users []map[string]interface{},
|
||||
userSvc *fakeSyncUsers, memberSvc *fakeSyncMembers, orgRepo *fakeSyncOrgRepo,
|
||||
) interfaces.CasdoorMemberSyncService {
|
||||
t.Helper()
|
||||
srv := fakeCasdoorServer(t, users)
|
||||
cfg := &config.Config{OIDCAuth: &config.OIDCAuthConfig{
|
||||
AdminAPIEnabled: true,
|
||||
AdminBaseURL: srv.URL,
|
||||
ClientID: "cid",
|
||||
ClientSecret: "cs",
|
||||
AdminOrganization: "built-in",
|
||||
EmailFallbackDomain: "casdoor.local",
|
||||
}}
|
||||
orgSvc := NewOrgCenterService(orgRepo, nil, nil, nil)
|
||||
return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc)
|
||||
}
|
||||
|
||||
// TestSyncCasdoorProvisionsAndJoins 全新目录:自动开户 + viewer 入空间 + 部门新建。
|
||||
func TestSyncCasdoorProvisionsAndJoins(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
svc := newSyncService(t, []map[string]interface{}{
|
||||
casdoorUser("26040006", "刘义亮", "liu@example.com", map[string]interface{}{
|
||||
"department": "仓储课",
|
||||
"departmentCode": "0002",
|
||||
}),
|
||||
casdoorUser("26080007", "孙凯", "", map[string]interface{}{ // 无邮箱 → 合成占位
|
||||
"department": "财务部",
|
||||
"departmentCode": "0001",
|
||||
}),
|
||||
}, userSvc, memberSvc, orgRepo)
|
||||
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers: %v", err)
|
||||
}
|
||||
if res.Total != 2 || res.UsersCreated != 2 || res.MembersAdded != 2 || res.DeptsCreated != 2 {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
if len(res.Skipped) != 0 {
|
||||
t.Fatalf("unexpected skips: %+v", res.Skipped)
|
||||
}
|
||||
// 无邮箱用户合成 <工号>@casdoor.local。
|
||||
u := userSvc.byUsername["26080007"]
|
||||
if u.Email != "26080007@casdoor.local" {
|
||||
t.Fatalf("synthesized email mismatch: %q", u.Email)
|
||||
}
|
||||
if u.DeptCode != "0001" || u.DeptName != "财务部" {
|
||||
t.Fatalf("dept not written: %+v", u)
|
||||
}
|
||||
// 部门落到组织架构(编号+名称)。
|
||||
found := map[string]string{}
|
||||
for _, d := range orgRepo.depts {
|
||||
found[d.Name] = d.Code
|
||||
}
|
||||
if found["仓储课"] != "0002" || found["财务部"] != "0001" {
|
||||
t.Fatalf("depts not created with codes: %+v", found)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorMatchesExistingByEmployeeNo 工号优先匹配:已有本地账号
|
||||
// (邮箱为合成占位)不重复开户;部门/姓名回写。
|
||||
func TestSyncCasdoorMatchesExistingByEmployeeNo(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers(&types.User{
|
||||
ID: "u-exist",
|
||||
Username: "26040006",
|
||||
Email: "26040006@casdoor.local", // 本地合成邮箱,与 Casdoor 真实邮箱不同
|
||||
})
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{depts: []*types.OrgDept{{ID: "d-ck", Name: "仓储课", Code: "0002"}}}
|
||||
svc := newSyncService(t, []map[string]interface{}{
|
||||
casdoorUser("26040006", "刘义亮", "liu@real.com", map[string]interface{}{
|
||||
"department": "仓储课",
|
||||
"departmentCode": "0002",
|
||||
}),
|
||||
}, userSvc, memberSvc, orgRepo)
|
||||
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers: %v", err)
|
||||
}
|
||||
if res.UsersCreated != 0 {
|
||||
t.Fatalf("existing user re-created: %+v", res)
|
||||
}
|
||||
if res.MembersAdded != 1 || res.DeptsCreated != 0 {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
u := userSvc.byUsername["26040006"]
|
||||
if u.DeptName != "仓储课" || u.DeptCode != "0002" {
|
||||
t.Fatalf("dept not refreshed on existing user: %+v", u)
|
||||
}
|
||||
// 邮箱不同也不另建账号:目录里仍只有原账号。
|
||||
if len(userSvc.created) != 0 {
|
||||
t.Fatalf("unexpected new accounts: %v", userSvc.created)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorIdempotent 第二次同步:不再重复开户/加成员,计数落到 existing。
|
||||
func TestSyncCasdoorIdempotent(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
users := []map[string]interface{}{
|
||||
casdoorUser("26080007", "孙凯", "sun@example.com", map[string]interface{}{"department": "财务部"}),
|
||||
}
|
||||
svc := newSyncService(t, users, userSvc, memberSvc, orgRepo)
|
||||
|
||||
if _, err := svc.SyncMembers(context.Background(), 7, "op-1"); err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
if res.UsersCreated != 0 || res.MembersAdded != 0 || res.MembersExist != 1 {
|
||||
t.Fatalf("second sync not idempotent: %+v", res)
|
||||
}
|
||||
if res.DeptsCreated != 0 { // 部门已存在,名称命中不重建
|
||||
t.Fatalf("dept re-created on second sync: %+v", res)
|
||||
}
|
||||
if len(memberSvc.added) != 1 {
|
||||
t.Fatalf("duplicate membership rows: %+v", memberSvc.added)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorSkipsDisabled 目录里的停用/删号/无工号用户逐条跳过,不阻断整批。
|
||||
func TestSyncCasdoorSkipsDisabled(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
svc := newSyncService(t, []map[string]interface{}{
|
||||
casdoorUser("26080007", "孙凯", "sun@example.com", nil),
|
||||
func() map[string]interface{} {
|
||||
u := casdoorUser("26090001", "张三", "zhang@example.com", nil)
|
||||
u["isForbidden"] = true
|
||||
return u
|
||||
}(),
|
||||
func() map[string]interface{} {
|
||||
u := casdoorUser("26090002", "李四", "li@example.com", nil)
|
||||
u["isDeleted"] = true
|
||||
return u
|
||||
}(),
|
||||
casdoorUser("", "无工号", "noname@example.com", nil),
|
||||
}, userSvc, memberSvc, orgRepo)
|
||||
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers: %v", err)
|
||||
}
|
||||
if res.MembersAdded != 1 || len(res.Skipped) != 3 {
|
||||
t.Fatalf("skip logic broken: added=%d skipped=%+v", res.MembersAdded, res.Skipped)
|
||||
}
|
||||
if userSvc.byUsername["26090001"] != nil || userSvc.byUsername["26090002"] != nil {
|
||||
t.Fatalf("disabled users were provisioned")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorWithoutDeptData 无部门数据自动降级:不建部门,成员照常同步。
|
||||
func TestSyncCasdoorWithoutDeptData(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
svc := newSyncService(t, []map[string]interface{}{
|
||||
casdoorUser("26080007", "孙凯", "sun@example.com", nil),
|
||||
}, userSvc, memberSvc, orgRepo)
|
||||
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers: %v", err)
|
||||
}
|
||||
if res.DeptsCreated != 0 || res.DeptSource != "" {
|
||||
t.Fatalf("dept sync should degrade silently: %+v", res)
|
||||
}
|
||||
if res.MembersAdded != 1 {
|
||||
t.Fatalf("member sync broken: %+v", res)
|
||||
}
|
||||
if u := userSvc.byUsername["26080007"]; u.DeptName != "" || u.DeptCode != "" {
|
||||
t.Fatalf("empty dept should not be written: %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorGrantNotSupported 未开 Client Credentials → 返回可操作提示。
|
||||
func TestSyncCasdoorGrantNotSupported(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
srv := fakeCasdoorServer(t, nil)
|
||||
// 换掉 token 端点:直接指向不支持该 grant 的假端点。
|
||||
mux := srv.Config.Handler
|
||||
_ = mux
|
||||
cfg := &config.Config{OIDCAuth: &config.OIDCAuthConfig{
|
||||
AdminAPIEnabled: true,
|
||||
AdminBaseURL: srv.URL,
|
||||
ClientID: "", // grant_type 校验在假端点里只认 client_id 非空
|
||||
ClientSecret: "cs",
|
||||
AdminOrganization: "built-in",
|
||||
}}
|
||||
// ClientID 为空 → client.Enabled() 为 false → 配置提示路径。
|
||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||
_, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err == nil || !strings.Contains(err.Error(), "未启用") {
|
||||
t.Fatalf("disabled config should surface actionable error, got: %v", err)
|
||||
}
|
||||
_ = casdoor.ErrGrantNotSupported // 保持导入被用(防 unused 提示)
|
||||
}
|
||||
|
||||
// TestSyncCasdoorPasswordMode 服务账号密码模式:username/password 走 password
|
||||
// grant 换用户令牌(部分 Casdoor 部署的 API 鉴权拒绝 client_credentials)。
|
||||
func TestSyncCasdoorPasswordMode(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
srv := fakeCasdoorServer(t, []map[string]interface{}{
|
||||
casdoorUser("26040006", "刘义亮", "liu@example.com", map[string]interface{}{
|
||||
"department": "仓储课",
|
||||
"departmentCode": "0002",
|
||||
}),
|
||||
})
|
||||
cfg := &config.Config{OIDCAuth: &config.OIDCAuthConfig{
|
||||
AdminAPIEnabled: true,
|
||||
AdminBaseURL: srv.URL,
|
||||
ClientID: "cid",
|
||||
ClientSecret: "cs",
|
||||
AdminOrganization: "organization_HX",
|
||||
AdminUsername: "svc-academy-sync", // 密码模式
|
||||
AdminPassword: "secret-pwd",
|
||||
EmailFallbackDomain: "casdoor.local",
|
||||
}}
|
||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers(password mode): %v", err)
|
||||
}
|
||||
if res.MembersAdded != 1 || res.DeptsCreated != 1 {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
if u := userSvc.byUsername["26040006"]; u.DeptCode != "0002" || u.DeptName != "仓储课" {
|
||||
t.Fatalf("dept not written in password mode: %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncCasdoorWrappedPayload 信封形态响应(部分 Casdoor 构建返回
|
||||
// {"status":"ok","data":[...]}) 与裸数组等价处理。
|
||||
func TestSyncCasdoorWrappedPayload(t *testing.T) {
|
||||
userSvc := newFakeSyncUsers()
|
||||
memberSvc := newFakeSyncMembers()
|
||||
orgRepo := &fakeSyncOrgRepo{}
|
||||
srv := fakeCasdoorServer(t, []map[string]interface{}{
|
||||
casdoorUser("26080007", "孙凯", "sun@example.com", nil),
|
||||
}, true)
|
||||
|
||||
cfg := &config.Config{OIDCAuth: &config.OIDCAuthConfig{
|
||||
AdminAPIEnabled: true,
|
||||
AdminBaseURL: srv.URL,
|
||||
ClientID: "cid",
|
||||
ClientSecret: "cs",
|
||||
AdminOrganization: "organization_HX",
|
||||
AdminUsername: "svc-academy-sync",
|
||||
AdminPassword: "secret-pwd",
|
||||
EmailFallbackDomain: "casdoor.local",
|
||||
}}
|
||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||
if err != nil {
|
||||
t.Fatalf("SyncMembers(wrapped): %v", err)
|
||||
}
|
||||
if res.MembersAdded != 1 {
|
||||
t.Fatalf("wrapped payload not parsed: %+v", res)
|
||||
}
|
||||
}
|
||||
@@ -272,7 +272,7 @@ func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo
|
||||
// tests pre-date PR 6 and exercise membership invariants only. The
|
||||
// service's audit and RemoveMember-cleanup hooks are nil-safe, so
|
||||
// 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
|
||||
@@ -359,7 +359,7 @@ func TestTenantMemberService_RemoveMember_ClearsStaleHomeAndRevokesTokens(t *tes
|
||||
},
|
||||
}}
|
||||
tokenRepo := &cleanupTokenRepo{}
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||
@@ -396,7 +396,7 @@ func TestTenantMemberService_RemoveMember_RevokesTokensEvenWhenHomeUnchanged(t *
|
||||
"contrib": {ID: "contrib", TenantID: 1},
|
||||
}}
|
||||
tokenRepo := &cleanupTokenRepo{}
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||
|
||||
@@ -38,11 +38,16 @@ type trainingService struct {
|
||||
chunkSvc interfaces.ChunkService
|
||||
// db 供 OA 企微 userid 同步直查 org_employees(见 training_scheduler 之外的 oa 集成)。
|
||||
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.
|
||||
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 {
|
||||
return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db}
|
||||
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, users: users, wecomOAuth: wecomOAuth}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -291,6 +296,25 @@ func (s *trainingService) CurrentMember(ctx context.Context, tenantID uint64, us
|
||||
}, 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 填充员工档案的培训模块绑定角色展示字段。
|
||||
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)
|
||||
@@ -372,6 +396,8 @@ func (s *trainingService) EnsureLecturerRole(ctx context.Context, tenantID uint6
|
||||
// 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) {
|
||||
// 编辑场景的存量值(课程关联保留口径,见下方课程校验)。
|
||||
var prevLibraryCourseID, prevCourseName string
|
||||
if demand.CourseName == "" {
|
||||
return nil, errors.NewBadRequestError("课程名称不能为空")
|
||||
}
|
||||
@@ -393,6 +419,10 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
if existing.Status == types.TrainingDemandConfirmed {
|
||||
return nil, errors.NewBadRequestError("已确认的需求不可编辑")
|
||||
}
|
||||
// 编辑保留原课程关联(000158):课程名未变时跳过重匹配,匹配失败时不
|
||||
// 清空已有关联(UpdateDemand 全量更新,零值会误清)。
|
||||
prevLibraryCourseID = existing.LibraryCourseID
|
||||
prevCourseName = existing.CourseName
|
||||
}
|
||||
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
|
||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||
@@ -413,6 +443,33 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
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 == "" {
|
||||
demand.ID = trainingNewID()
|
||||
demand.TenantID = tenantID
|
||||
@@ -431,10 +488,14 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return nil, errors.NewBadRequestError("导入数据为空")
|
||||
return nil, 0, errors.NewBadRequestError("导入数据为空")
|
||||
}
|
||||
// 课程校验批内去重(000158):同名行只查/建一次,其余行复用条目 id。
|
||||
courseCache := map[string]string{}
|
||||
coursesCreated := 0
|
||||
for i := range demands {
|
||||
demands[i].ID = trainingNewID()
|
||||
demands[i].TenantID = tenantID
|
||||
@@ -450,17 +511,51 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
|
||||
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
|
||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
|
||||
// 讲师口径互斥与 SaveDemand 一致:系统员工优先,外部姓名仅在无 id 时生效。
|
||||
if demands[i].LecturerID != "" {
|
||||
demands[i].LecturerExternal = ""
|
||||
}
|
||||
msgs := []string{}
|
||||
if demands[i].DeptID == "" {
|
||||
msgs = append(msgs, "未指定部门")
|
||||
}
|
||||
demands[i].CheckMsg = strings.Join(msgs, ";")
|
||||
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 {
|
||||
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
|
||||
|
||||
@@ -130,9 +130,12 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
|
||||
}
|
||||
|
||||
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
|
||||
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/
|
||||
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。
|
||||
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
|
||||
// 课程名称/类型随课程管理主数据锁定;形式(mode)为计划侧独立字段——计划形式
|
||||
// 指本次培训线上办还是线下办,与课程主数据的线上课/线下课口径不同,不随课程
|
||||
// 带出,由创建/调整表单自行选择;讲师 000161 起计划侧可改(更新路径不再覆盖,
|
||||
// 改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时讲师/学时/
|
||||
// 课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存
|
||||
// (fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
|
||||
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
|
||||
if course.LibraryCourseID == "" {
|
||||
return nil
|
||||
@@ -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)
|
||||
return nil
|
||||
}
|
||||
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖。
|
||||
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖(形式除外,见上)。
|
||||
course.Name = item.Name
|
||||
course.Type = item.Type
|
||||
course.Mode = item.Mode
|
||||
if item.LecturerID != "" || item.LecturerExternal != "" {
|
||||
if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") {
|
||||
// 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。
|
||||
course.LecturerID = item.LecturerID
|
||||
course.LecturerExternal = item.LecturerExternal
|
||||
}
|
||||
@@ -172,6 +175,35 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
|
||||
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,新建计划时):
|
||||
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
|
||||
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
|
||||
@@ -232,8 +264,8 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
|
||||
return course, nil
|
||||
}
|
||||
course.TenantID = tenantID
|
||||
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。
|
||||
s.applyLibraryCourseBinding(ctx, tenantID, course, false)
|
||||
// 课程管理关联存在时锁定带出字段(000153;讲师 000161 起计划侧可改)。
|
||||
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, false)
|
||||
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
|
||||
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
|
||||
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 {
|
||||
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 {
|
||||
s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID)
|
||||
}
|
||||
@@ -358,6 +394,56 @@ func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id
|
||||
if course.Status == types.TrainingCoursePublished {
|
||||
return course, nil
|
||||
}
|
||||
// 发布必填校验(000161):课程(须关联课程管理且已签核)、参加人员;
|
||||
// 线下计划另需授课时间/授课地点/讲师(线上计划豁免这三项)。
|
||||
if strings.TrimSpace(course.LibraryCourseID) == "" {
|
||||
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
|
||||
}
|
||||
hasLibCourseware := strings.TrimSpace(lib.MaterialName) != "" ||
|
||||
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
|
||||
if err := s.repo.UpdateCourse(ctx, course); err != nil {
|
||||
return nil, err
|
||||
@@ -567,8 +653,40 @@ func (s *trainingService) CreateMaterial(ctx context.Context, tenantID uint64, m
|
||||
}
|
||||
|
||||
// ListMaterials returns course materials.
|
||||
// 计划未自带课件时回退关联课程的课程管理课件(000156 随课程带出,发布校验同口径):
|
||||
// 以课程管理条目 id 作为虚拟课件 id 返回,学习详情页预览/文件流/进度上报同链路可用
|
||||
// (GetMaterialFile 对虚拟 id 回退课程管理文件流);仅登记名称而无文件/知识库文档时
|
||||
// 不合成(无内容可打开)。
|
||||
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 指向课程,
|
||||
@@ -593,6 +711,8 @@ func (s *trainingService) AttachQuestionBank(ctx context.Context, tenantID uint6
|
||||
|
||||
// CreateSignCode generates (or refreshes) the session's sign-in code with an
|
||||
// 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) {
|
||||
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
|
||||
if err != nil {
|
||||
@@ -601,12 +721,19 @@ func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, s
|
||||
if radius <= 0 {
|
||||
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 candidate := session.StartAt.Add(4 * time.Hour); candidate.After(time.Now()) {
|
||||
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
|
||||
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{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
@@ -629,22 +756,86 @@ func trainingNewToken() string {
|
||||
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) {
|
||||
code, err := s.repo.GetSignCodeBySession(ctx, tenantID, sessionID)
|
||||
if err != nil {
|
||||
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:
|
||||
// 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 配置。
|
||||
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)
|
||||
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) {
|
||||
return nil, errors.NewBadRequestError("签到码已过期")
|
||||
@@ -661,7 +852,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
|
||||
}
|
||||
|
||||
// 名单校验(名单外人员自动标记)。
|
||||
// 名单校验(名单外人员自动标记;严格模式下直接拒绝,见下)。
|
||||
roster, err := s.repo.ListEnrollments(ctx, tenantID, session.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -675,6 +866,47 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
}
|
||||
|
||||
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{}
|
||||
status := types.TrainingSignNormal
|
||||
|
||||
@@ -695,7 +927,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
}
|
||||
}
|
||||
|
||||
// 名单外人员标记。
|
||||
// 名单外人员标记(工号严格链路已在上方硬拒,此处仅既有登录态路径可达)。
|
||||
if !inRoster {
|
||||
flags = append(flags, "not_in_roster")
|
||||
status = types.TrainingSignAbnormal
|
||||
@@ -706,6 +938,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
return nil, errors.NewBadRequestError("您已签到,请勿重复扫码")
|
||||
}
|
||||
|
||||
channel := in.Channel
|
||||
if channel == "" {
|
||||
channel = "wecom_scan"
|
||||
}
|
||||
@@ -721,6 +954,7 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
Lng: lng,
|
||||
DistanceM: distance,
|
||||
Status: status,
|
||||
Nonce: strings.TrimSpace(in.Nonce),
|
||||
AbnormalFlags: flagsJSON,
|
||||
}
|
||||
if err := s.repo.UpsertSignRecord(ctx, record); err != nil {
|
||||
@@ -734,6 +968,28 @@ func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID,
|
||||
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.
|
||||
func haversineMeters(lat1, lng1, lat2, lng2 float64) float64 {
|
||||
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)
|
||||
}
|
||||
|
||||
// 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
|
||||
// (管理端「学习考试」课程学习情况;任务不存在但已发布课程的名单成员由前端按待学习渲染口径,此处按实际任务行返回)。
|
||||
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) {
|
||||
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
|
||||
if err != nil {
|
||||
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
|
||||
// 材料行不存在时按课程管理条目取文件流,与发布/学习链路同口径。
|
||||
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID); libErr == nil {
|
||||
return rc, fileName, nil
|
||||
}
|
||||
return nil, "", werrors.NewNotFoundError("课件不存在")
|
||||
}
|
||||
if material.KnowledgeID != "" {
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
@@ -9,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
excelize "github.com/xuri/excelize/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
werrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
@@ -103,8 +105,15 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 新增即待核验(000157):由所属部门课长/经理核验后方可发布。
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
|
||||
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-####,创建时由服务端生成;编号列只读,不收前端值)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||
@@ -129,6 +138,12 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
||||
if item.KnowledgeID == "" {
|
||||
item.KnowledgeID = old.KnowledgeID
|
||||
}
|
||||
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
|
||||
item.OwnerDeptID = old.OwnerDeptID
|
||||
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
item.ConfirmedBy = ""
|
||||
item.ConfirmedAt = nil
|
||||
item.TenantID = tenantID
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
@@ -137,10 +152,19 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem 软删课程管理条目(月培训计划已创建的历史计划不受影响)。
|
||||
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error {
|
||||
if _, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id); err != nil {
|
||||
// 000157 收紧:仅「待核验」状态可删(已确认课程须走核验流程,不可绕过);
|
||||
// deptScope 非空(课长/经理)时仅可删除本部门课程。
|
||||
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string) error {
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if item.VerifyStatus != types.CourseLibraryVerifyPending {
|
||||
return werrors.NewBadRequestError("仅待核验状态的课程可删除,已确认课程不可删除")
|
||||
}
|
||||
if deptScope != "" && item.OwnerDeptID != deptScope {
|
||||
return werrors.NewForbiddenError("仅可删除本部门的课程")
|
||||
}
|
||||
return s.repo.DeleteCourseLibraryItem(ctx, tenantID, id)
|
||||
}
|
||||
|
||||
@@ -155,6 +179,8 @@ func (s *trainingService) GetCourseLibraryItem(ctx context.Context, tenantID uin
|
||||
|
||||
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 /
|
||||
// offline 已下线;培训中心「和信课程」目录仅展示已发布课程。
|
||||
// 发布前置校验核验状态(000157):仅「已确认」课程可发布;
|
||||
// 发布必须有课件(名称登记不算,须已上传课件文件或已挂接知识库课件文档)。
|
||||
func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
|
||||
if status != "published" && status != "offline" {
|
||||
return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)")
|
||||
@@ -163,9 +189,90 @@ func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, ten
|
||||
if err != nil || item == nil {
|
||||
return werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name))
|
||||
}
|
||||
if status == "published" && strings.TrimSpace(item.FileKey) == "" && strings.TrimSpace(item.KnowledgeID) == "" {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name))
|
||||
}
|
||||
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
|
||||
}
|
||||
|
||||
// VerifyCourseLibraryItems 批量核验课程条目(000157,单个/批量共用):核验人所在
|
||||
// 部门(deptScope,handler 保证恒非空)必须与课程所属部门一致;已确认行与部门
|
||||
// 不匹配行跳过,返回实际核验数与跳过数,全无效时报错提示。
|
||||
func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (int64, int64, error) {
|
||||
allowed := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
continue // 不存在的条目跳过,不阻断其余行
|
||||
}
|
||||
if item.VerifyStatus != types.CourseLibraryVerifyPending {
|
||||
continue // 已确认行幂等跳过
|
||||
}
|
||||
if deptScope != "" && item.OwnerDeptID != deptScope {
|
||||
continue // 课长/经理仅可核验本部门课程
|
||||
}
|
||||
allowed = append(allowed, id)
|
||||
}
|
||||
skipped := int64(len(ids) - len(allowed))
|
||||
if len(allowed) == 0 {
|
||||
return 0, skipped, werrors.NewBadRequestError("没有可核验的课程(仅本部门待核验状态的课程可核验)")
|
||||
}
|
||||
verified, err := s.repo.ConfirmCourseLibraryItems(ctx, tenantID, allowed, verifierID)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
logger.Infof(ctx, "[Training] course library verified, tenant=%d verified=%d skipped=%d verifier=%s", tenantID, verified, skipped, verifierID)
|
||||
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 后逐行提交,讲师已在
|
||||
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
||||
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
||||
@@ -182,6 +289,8 @@ func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 导入即待核验(000157):与新增同口径,核验后方可发布。
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
// 课程编号逐行生成(CRS-####)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
rows = append(rows, item)
|
||||
@@ -290,6 +399,10 @@ func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenan
|
||||
if strings.TrimSpace(item.MaterialName) == "" {
|
||||
item.MaterialName = fh.Filename
|
||||
}
|
||||
// 换课件即回待核验(000157):课件内容变更后需重新核验。
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
item.ConfirmedBy = ""
|
||||
item.ConfirmedAt = nil
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -325,6 +438,29 @@ func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tena
|
||||
return rc, item.FileName, nil
|
||||
}
|
||||
|
||||
// RemoveCourseLibraryMaterial 移除课程课件原始文件/知识库挂接(名称登记保留,
|
||||
// 上传课件时仍会以文件名兜底名称登记):文件与知识库文档字段清空,课件内容
|
||||
// 变更即回待核验(000157 同口径),移除后课程不满足发布课件前置。
|
||||
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
|
||||
if err != nil || item == nil {
|
||||
return nil, werrors.NewNotFoundError("课程不存在")
|
||||
}
|
||||
if item.FileKey == "" && item.KnowledgeID == "" {
|
||||
return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除")
|
||||
}
|
||||
item.FileKey, item.FileName, item.FileSize = "", "", 0
|
||||
item.KnowledgeID = ""
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
item.ConfirmedBy = ""
|
||||
item.ConfirmedAt = nil
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s operator=%s", tenantID, id, updaterID)
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
|
||||
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
|
||||
// 原始文件字段清空,名称登记为空时以文档名兜底。
|
||||
@@ -353,6 +489,10 @@ func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.C
|
||||
}
|
||||
item.FileKey, item.FileSize = "", 0
|
||||
item.KnowledgeID = knowledgeID
|
||||
// 换课件即回待核验(000157):课件内容变更后需重新核验。
|
||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||
item.ConfirmedBy = ""
|
||||
item.ConfirmedAt = nil
|
||||
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -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("成员不存在")
|
||||
}
|
||||
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 走完整校验。
|
||||
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 {
|
||||
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
|
||||
}
|
||||
@@ -98,14 +98,18 @@ func getJwtSecret() string {
|
||||
|
||||
// userService implements the UserService interface
|
||||
type userService struct {
|
||||
userRepo interfaces.UserRepository
|
||||
tokenRepo interfaces.AuthTokenRepository
|
||||
tenantService interfaces.TenantService
|
||||
memberService interfaces.TenantMemberService
|
||||
userRepo interfaces.UserRepository
|
||||
tokenRepo interfaces.AuthTokenRepository
|
||||
tenantService interfaces.TenantService
|
||||
memberService interfaces.TenantMemberService
|
||||
invitationService interfaces.TenantInvitationService
|
||||
config *config.Config
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
sandboxReleaser SandboxOwnerReleaser
|
||||
config *config.Config
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
sandboxReleaser SandboxOwnerReleaser
|
||||
// bootstrap is optional (nil in unit tests): seeds out-of-the-box
|
||||
// defaults (starter KB + tenant rerank) into freshly created personal
|
||||
// workspaces. Fail-open by contract — see TenantBootstrapService.
|
||||
bootstrap interfaces.TenantBootstrapService
|
||||
}
|
||||
|
||||
// NewUserService creates a new user service instance
|
||||
@@ -117,6 +121,7 @@ func NewUserService(
|
||||
memberService interfaces.TenantMemberService,
|
||||
invitationService interfaces.TenantInvitationService,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
bootstrap interfaces.TenantBootstrapService,
|
||||
) interfaces.UserService {
|
||||
return &userService{
|
||||
userRepo: userRepo,
|
||||
@@ -126,6 +131,7 @@ func NewUserService(
|
||||
invitationService: invitationService,
|
||||
config: configInfo,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
bootstrap: bootstrap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,6 +232,13 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
|
||||
}
|
||||
|
||||
logger.Info(ctx, "User registered successfully")
|
||||
|
||||
// 开箱即用:为新个人空间 seed 默认模型配置(入门知识库 + 欢迎文档 +
|
||||
// 租户级重排模型)。整体 fail-open,任何失败不影响注册结果。
|
||||
if createdTenant != nil && s.bootstrap != nil {
|
||||
s.bootstrap.SeedTenantDefaults(ctx, createdTenant, user.ID)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
@@ -311,6 +324,39 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
|
||||
}, 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
|
||||
// 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
|
||||
|
||||
@@ -380,6 +380,25 @@ type OIDCAuthConfig struct {
|
||||
// 前端登录表单直接提交工号+密码,由后端转发 IdP token 端点校验,
|
||||
// 浏览器不接触 client_secret。要求 IdP 应用 grantTypes 勾选 password。
|
||||
PasswordLoginEnabled bool `yaml:"password_login_enabled" json:"password_login_enabled"`
|
||||
// ---------------------------------------------------------------------------
|
||||
// Casdoor 管理 API(成员同步专用,000156):后端以 client_credentials 拿
|
||||
// token 后调 /api/get-users 拉用户列表做「同步 Casdoor 成员」。需要 Casdoor
|
||||
// 应用 grantTypes 勾选 Client Credentials,且凭据具备管理权限。
|
||||
// AdminBaseURL 留空时从 IssuerURL/TokenEndpoint 推导(scheme+host)。
|
||||
// AdminOrganization 是 get-users 的 owner 参数(Casdoor 组织名,built-in
|
||||
// 为默认组织);DeptFields 留空时按内置候选顺序探测(groups → affiliation
|
||||
// → title → properties.department)。
|
||||
AdminAPIEnabled bool `yaml:"admin_api_enabled" json:"-"`
|
||||
AdminBaseURL string `yaml:"admin_base_url" json:"-"`
|
||||
AdminOrganization string `yaml:"admin_organization" json:"-"`
|
||||
AdminDeptField string `yaml:"admin_dept_field" json:"-"` // 部门名称取值字段,空=自动探测
|
||||
AdminDeptCodeField string `yaml:"admin_dept_code_field" json:"-"` // 部门编号取值字段,空=自动探测
|
||||
// AdminUsername/AdminPassword 服务账号密码模式(推荐):部分 Casdoor 部署的
|
||||
// API 鉴权(casbin)会拒绝 client_credentials 的应用令牌调管理接口,此时改用
|
||||
// 组织管理员的 password grant 换用户令牌。两项都非空时优先走密码模式,
|
||||
// 否则回落 client_credentials。账号需具备目标组织的管理权限(is_admin)。
|
||||
AdminUsername string `yaml:"admin_username" json:"-"`
|
||||
AdminPassword string `yaml:"admin_password" json:"-"`
|
||||
}
|
||||
|
||||
// PromptTemplateI18n holds localized name and description for a prompt template.
|
||||
@@ -807,6 +826,32 @@ func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_EMAIL_FALLBACK_DOMAIN")); value != "" {
|
||||
cfg.OIDCAuth.EmailFallbackDomain = value
|
||||
}
|
||||
// Casdoor 管理 API(成员同步,000156):开关/组织/部门字段映射。
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_API_ENABLE")); value != "" {
|
||||
cfg.OIDCAuth.AdminAPIEnabled = strings.EqualFold(value, "true")
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_BASE_URL")); value != "" {
|
||||
cfg.OIDCAuth.AdminBaseURL = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_ORGANIZATION")); value != "" {
|
||||
cfg.OIDCAuth.AdminOrganization = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_DEPT_FIELD")); value != "" {
|
||||
cfg.OIDCAuth.AdminDeptField = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_DEPT_CODE_FIELD")); value != "" {
|
||||
cfg.OIDCAuth.AdminDeptCodeField = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_USERNAME")); value != "" {
|
||||
cfg.OIDCAuth.AdminUsername = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ADMIN_PASSWORD")); value != "" {
|
||||
cfg.OIDCAuth.AdminPassword = value
|
||||
}
|
||||
if cfg.OIDCAuth.AdminOrganization == "" {
|
||||
// Casdoor 默认组织名;get-users 的 owner 参数。
|
||||
cfg.OIDCAuth.AdminOrganization = "built-in"
|
||||
}
|
||||
|
||||
if cfg.OIDCAuth.ProviderDisplayName == "" {
|
||||
cfg.OIDCAuth.ProviderDisplayName = "OIDC"
|
||||
|
||||
@@ -260,6 +260,9 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewTenantService))
|
||||
must(container.Provide(service.NewTenantAPIKeyService))
|
||||
must(container.Provide(service.NewTenantMemberService))
|
||||
// Casdoor 成员目录同步(000156,成员管理「同步CASDOOR成员」)。
|
||||
must(container.Provide(service.NewCasdoorMemberSyncService))
|
||||
must(container.Provide(service.NewTenantBootstrapService))
|
||||
must(container.Provide(service.NewTenantInvitationService))
|
||||
must(container.Provide(service.NewAuditLogService))
|
||||
must(container.Provide(service.NewAuditLogRetentionRunner))
|
||||
@@ -410,6 +413,12 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
// Training domain (企业培训业务域): repo → service(interface) → handler.
|
||||
must(container.Provide(repository.NewTrainingRepository))
|
||||
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)
|
||||
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
|
||||
@@ -2178,6 +2187,17 @@ func (b trainingWecomBackend) TenantWecomUserIDs(ctx context.Context, db *gorm.D
|
||||
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
|
||||
// registers cleanup. Best-effort like the other background runners.
|
||||
func startTrainingScheduler(scheduler *service.TrainingScheduler, cleaner interfaces.ResourceCleaner) {
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestCustomAgentAvatarAndErrorResponses(t *testing.T) {
|
||||
agent: &types.CustomAgent{ID: "custom-1", Name: "old", Avatar: "🤖", TenantID: 1},
|
||||
err: tc.repoErr,
|
||||
}
|
||||
svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil)
|
||||
svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
h := &CustomAgentHandler{service: svc}
|
||||
router := gin.New()
|
||||
router.Use(middleware.ErrorHandler())
|
||||
|
||||
@@ -50,7 +50,7 @@ func servePatchWith(
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
h.service = service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil)
|
||||
h.service = service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
router := gin.New()
|
||||
router.Use(middleware.ErrorHandler())
|
||||
router.PATCH("/agents/:id", h.PatchAgent)
|
||||
|
||||
@@ -48,6 +48,9 @@ type KnowledgeBaseHandler struct {
|
||||
// default handle mode is available.
|
||||
fileService interfaces.FileService
|
||||
storageResolver interfaces.StorageBackendResolver
|
||||
// bootstrap 幂等自愈空间开箱默认库(新手入门/企业培训课件/题库),挂在
|
||||
// 知识库列表读路径上补齐存量空间缺失的默认库;可为 nil(测试桩)。
|
||||
bootstrap interfaces.TenantBootstrapService
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseHandler creates a new knowledge base handler instance
|
||||
@@ -63,6 +66,7 @@ func NewKnowledgeBaseHandler(
|
||||
fileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
profileService interfaces.KnowledgeBaseProfileService,
|
||||
bootstrap interfaces.TenantBootstrapService,
|
||||
) *KnowledgeBaseHandler {
|
||||
return &KnowledgeBaseHandler{
|
||||
cfg: cfg,
|
||||
@@ -76,6 +80,7 @@ func NewKnowledgeBaseHandler(
|
||||
userService: userService,
|
||||
fileService: fileService,
|
||||
storageResolver: storageResolver,
|
||||
bootstrap: bootstrap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +644,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 开箱默认库惰性自愈(幂等/fail-open):注册引导是一次性动作,存量空间因
|
||||
// 引导当时失败或保留租户 id 碰撞(migration 000160 前首空间占住 10000)
|
||||
// 而缺失默认库时,访问列表即补齐——培训课件/题库两库恒补,新手入门仅
|
||||
// 零库空间补建。补建后本次查询即可见。
|
||||
if h.bootstrap != nil {
|
||||
h.bootstrap.EnsureTenantDefaultKnowledgeBases(ctx)
|
||||
}
|
||||
|
||||
// Get all knowledge bases for this tenant
|
||||
kbs, err := h.service.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package orgcenter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -199,6 +200,69 @@ func (h *Handler) ListPlatformUsers(c *gin.Context) {
|
||||
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.
|
||||
type putModuleMemberRequest struct {
|
||||
Roles []string `json:"roles"`
|
||||
Extra map[string]any `json:"extra"`
|
||||
Roles []string `json:"roles"`
|
||||
Extra map[string]any `json:"extra"`
|
||||
}
|
||||
|
||||
// PutModuleMember PUT /org/modules/:module_key/members/:employee_id
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestSetUserStatus_NotFound404(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
|
||||
require.NoError(t, db.AutoMigrate(&types.User{}))
|
||||
svc := service.NewUserService(nil, repository.NewUserRepository(db), nil, nil, nil, nil, nil)
|
||||
svc := service.NewUserService(nil, repository.NewUserRepository(db), nil, nil, nil, nil, nil, nil)
|
||||
h := &SystemHandler{userSvc: svc}
|
||||
r := statusRouter(h, "admin-1")
|
||||
body, _ := json.Marshal(map[string]any{"user_id": "ghost", "is_active": true})
|
||||
|
||||
@@ -36,6 +36,10 @@ type TenantHandler struct {
|
||||
// in-code default, so a SystemAdmin's UI override applies on the
|
||||
// very next CreateTenant call.
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
// bootstrap seeds out-of-the-box defaults (starter KB bound to the
|
||||
// built-in default models, welcome doc, tenant rerank) into freshly
|
||||
// created workspaces. Optional; fail-open by contract.
|
||||
bootstrap interfaces.TenantBootstrapService
|
||||
}
|
||||
|
||||
// NewTenantHandler creates a new tenant handler instance with the provided service
|
||||
@@ -63,6 +67,7 @@ func NewTenantHandler(
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
config *config.Config,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
bootstrap interfaces.TenantBootstrapService,
|
||||
) *TenantHandler {
|
||||
return &TenantHandler{
|
||||
service: service,
|
||||
@@ -72,6 +77,7 @@ func NewTenantHandler(
|
||||
kbService: kbService,
|
||||
config: config,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
bootstrap: bootstrap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,12 +451,16 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 开箱即用:为新建空间 seed 默认模型配置(入门知识库 + 欢迎文档 +
|
||||
// 租户级重排模型)。整体 fail-open,任何失败不影响建租户结果。
|
||||
if h.bootstrap != nil {
|
||||
h.bootstrap.SeedTenantDefaults(ctx, createdTenant, caller.ID)
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Tenant created successfully, ID: %d, name: %s",
|
||||
createdTenant.ID,
|
||||
secutils.SanitizeForLog(createdTenant.Name),
|
||||
)
|
||||
createdTenant.ID, secutils.SanitizeForLog(createdTenant.Name))
|
||||
|
||||
// data carries the created tenant. When the legacy auto-create-key
|
||||
// behaviour is enabled we embed the plaintext token as data.api_key so
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
apprepo "academy/internal/application/repository"
|
||||
"academy/internal/application/service"
|
||||
"academy/internal/config"
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
@@ -35,20 +36,38 @@ import (
|
||||
type TenantMemberHandler struct {
|
||||
memberService interfaces.TenantMemberService
|
||||
userService interfaces.UserService
|
||||
// orgService 驱动批量导入的部门列自动匹配(读本租户部门管理 org_depts);
|
||||
// 未装配时导入照常进行,部门列整列忽略(handler 内 nil 兜底)。
|
||||
orgService interfaces.OrgCenterService
|
||||
// syncService 驱动「同步CASDOOR成员」(000156);未启用管理 API 时
|
||||
// 依赖仍注入(SyncMembers 返回配置提示),handler 只做 nil 兜底。
|
||||
syncService interfaces.CasdoorMemberSyncService
|
||||
// config is optional for the CRUD paths; ImportMembers reads
|
||||
// OIDCAuth.EmailFallbackDomain from it to synthesise placeholder
|
||||
// emails when a roster row has none (same source of truth as the
|
||||
// OIDC login path's synthesizeOIDCEmail).
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
// NewTenantMemberHandler wires the dependencies. PR 1 already provides
|
||||
// both services through the dig container; we just consume them. The
|
||||
// previous *config.Config argument was removed once
|
||||
// middleware.RequirePathTenantMatch took over the cross-tenant
|
||||
// superuser carve-out.
|
||||
// superuser carve-out; it is back for ImportMembers (placeholder-email
|
||||
// synthesis) and dig resolves it automatically.
|
||||
func NewTenantMemberHandler(
|
||||
memberService interfaces.TenantMemberService,
|
||||
userService interfaces.UserService,
|
||||
orgService interfaces.OrgCenterService,
|
||||
syncService interfaces.CasdoorMemberSyncService,
|
||||
cfg *config.Config,
|
||||
) *TenantMemberHandler {
|
||||
return &TenantMemberHandler{
|
||||
memberService: memberService,
|
||||
userService: userService,
|
||||
orgService: orgService,
|
||||
syncService: syncService,
|
||||
config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +166,7 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
|
||||
row.Email = u.Email
|
||||
row.Username = u.Username
|
||||
row.DisplayName = u.DisplayName
|
||||
row.DeptName = u.DeptName
|
||||
row.Avatar = u.Avatar
|
||||
}
|
||||
resp = append(resp, row)
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/application/service"
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 成员批量导入(设置 → 成员管理 → 批量导入)
|
||||
//
|
||||
// Owner 上传 HR 花名册 Excel(工号/姓名/部门/邮箱/角色),逐行解析后:
|
||||
// 1. 按邮箱、再按工号(users.username,见 000143 迁移的工号约定)匹配已有账号;
|
||||
// 2. 都未命中时自动创建本地账号——与 OIDC 首登自动开户(provisionOIDCUser)
|
||||
// 同模式:随机密码、tenantless(不建个人空间)、标记 OidcOnlyLogin,员工
|
||||
// 首次 Casdoor 登录时按邮箱命中或经 adoptOIDCUserByUsername 按工号收编;
|
||||
// 3. 直接加入当前空间(直加路径,AddMember 自带 rbac.member_added 审计)。
|
||||
//
|
||||
// 部门列自动匹配:花名册填写的部门名在本租户部门管理(org_depts)中
|
||||
// 按名称/编号自动匹配,命中即回写 users.dept_name/dept_code(成员列表
|
||||
// 「所属部门」列的展示口径,见 000156 迁移);未命中不阻断该行导入,
|
||||
// 部门字段留空。部门管理数据不可用时整列降级忽略(与 Casdoor 同步的
|
||||
// 无部门降级同思路)。
|
||||
//
|
||||
// 逐行容错:单行失败不阻断整批,结果逐行回传给 UI 展示。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const (
|
||||
// memberImportMaxFileMB 花名册小文件,5MB 足够(2000 行 × 5 列远小于此)。
|
||||
memberImportMaxFileMB = 5
|
||||
// memberImportMaxRows 单次导入行数上限,限制请求处理时长。
|
||||
memberImportMaxRows = 2000
|
||||
// memberImportHeaderScanRows 表头探测在前 N 行内进行(模板含示例/说明行时容错)。
|
||||
memberImportHeaderScanRows = 10
|
||||
// memberImportMaxHeaderCols 表头只看前 N 列,防止畸形宽表误配。
|
||||
memberImportMaxHeaderCols = 16
|
||||
)
|
||||
|
||||
// memberImportRowResult 是导入结果中的一行,status ∈ added / created / exists / failed。
|
||||
type memberImportRowResult struct {
|
||||
Row int `json:"row"`
|
||||
EmployeeNo string `json:"employee_no"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// memberImportRow 是 Excel 中的一行原始数据(Row 为 Excel 展示行号,从 1 起)。
|
||||
type memberImportRow struct {
|
||||
Row int
|
||||
EmployeeNo string
|
||||
Email string
|
||||
Name string
|
||||
Dept string // 部门列原文,导入时按部门管理自动匹配
|
||||
RoleRaw string
|
||||
}
|
||||
|
||||
// memberImportColumns 记录表头各列的下标;-1 表示该列缺失(姓名/部门/角色可缺省)。
|
||||
type memberImportColumns struct {
|
||||
employeeNo int
|
||||
email int
|
||||
name int
|
||||
dept int
|
||||
role int
|
||||
}
|
||||
|
||||
// ImportMembers godoc
|
||||
// @Summary 批量导入空间成员(Excel 模板)
|
||||
// @Description
|
||||
//
|
||||
// Owner 上传成员花名册 Excel(表头:工号/姓名/部门/邮箱/角色,可先下载模板),
|
||||
// 逐行导入当前空间:按邮箱、再按工号匹配已有账号;未注册的员工自动创建
|
||||
// 本地账号(随机密码、OIDC-only,首次登录自动收编)并直接加入空间。
|
||||
// 部门列按部门管理(org_depts)自动匹配,命中即回写成员所属部门,未命中留空。
|
||||
// 单行失败不阻断整批,响应逐行回传结果与原因。
|
||||
//
|
||||
// @Tags 空间成员
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param id path string true "空间 ID"
|
||||
// @Param file formData file true "成员导入 Excel(.xlsx/.xls)"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /tenants/{id}/members/import [post]
|
||||
func (h *TenantMemberHandler) ImportMembers(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID, ok := parseTenantIDFromPath(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 限流在 multipart 解析之前(同 knowledge.go:FormFile 会先缓冲整个 body,
|
||||
// 解析后再查就等于已经全量接受了上传)。
|
||||
maxBytes := int64(memberImportMaxFileMB) * 1024 * 1024
|
||||
limitUploadBody(c, maxBytes)
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
if isRequestBodyTooLarge(err) {
|
||||
c.Error(apperrors.NewValidationError(
|
||||
fmt.Sprintf("文件大小不能超过 %dMB", memberImportMaxFileMB)))
|
||||
return
|
||||
}
|
||||
c.Error(apperrors.NewValidationError("缺少上传文件"))
|
||||
return
|
||||
}
|
||||
fh, err := file.Open()
|
||||
if err != nil {
|
||||
c.Error(apperrors.NewValidationError("读取上传文件失败").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
data, err := readAllImportBytes(fh)
|
||||
if err != nil {
|
||||
c.Error(apperrors.NewValidationError("读取上传文件失败").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := parseMemberImportExcel(data)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// 部门列自动匹配器:一次性快照本租户部门管理,逐行匹配。部门管理
|
||||
// 不可用(服务缺失/查询失败)时返回 nil,部门列整列降级忽略。
|
||||
deptMatcher := h.loadImportDeptMatcher(ctx, tenantID)
|
||||
|
||||
// 兜底域用于邮箱缺失时合成占位地址(与 synthesizeOIDCEmail 同源配置)。
|
||||
fallbackDomain := ""
|
||||
if h.config != nil && h.config.OIDCAuth != nil {
|
||||
fallbackDomain = h.config.OIDCAuth.EmailFallbackDomain
|
||||
}
|
||||
|
||||
// Attribute the import to a human caller only (synthetic API-key
|
||||
// principals must not become invited_by — same treatment as AddMember).
|
||||
caller, _ := types.UserIDFromContext(ctx)
|
||||
var invitedBy *string
|
||||
if caller != "" && !types.IsSyntheticUserID(caller) {
|
||||
invitedBy = &caller
|
||||
}
|
||||
|
||||
results, added, created, exists, failed := h.processMemberImportRows(
|
||||
ctx, tenantID, rows, deptMatcher, fallbackDomain, invitedBy)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"total": len(rows),
|
||||
"added": added,
|
||||
"created_accounts": created,
|
||||
"already_member": exists,
|
||||
"failed": failed,
|
||||
"results": results,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// processMemberImportRows 逐行校验、匹配/开户、加入空间,返回逐行结果与计数。
|
||||
// deptMatcher 为 nil 时部门列忽略(部门管理不可用的降级形态)。
|
||||
func (h *TenantMemberHandler) processMemberImportRows(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
rows []memberImportRow,
|
||||
deptMatcher *memberImportDeptMatcher,
|
||||
fallbackDomain string,
|
||||
invitedBy *string,
|
||||
) (results []memberImportRowResult, added, created, exists, failed int) {
|
||||
results = make([]memberImportRowResult, 0, len(rows))
|
||||
seenUserIDs := map[string]bool{}
|
||||
seenIdentities := map[string]bool{} // 键:小写邮箱 / 小写工号,文件内去重
|
||||
|
||||
for _, row := range rows {
|
||||
res := memberImportRowResult{
|
||||
Row: row.Row,
|
||||
EmployeeNo: row.EmployeeNo,
|
||||
Email: row.Email,
|
||||
Name: row.Name,
|
||||
}
|
||||
fail := func(reason string) {
|
||||
res.Status = "failed"
|
||||
res.Reason = reason
|
||||
results = append(results, res)
|
||||
failed++
|
||||
}
|
||||
|
||||
// --- 行校验 ------------------------------------------------------
|
||||
if row.EmployeeNo == "" {
|
||||
fail("工号为空")
|
||||
continue
|
||||
}
|
||||
if len(row.EmployeeNo) > 50 {
|
||||
// 与 RegisterRequest binding 的 max=50 保持一致。
|
||||
fail("工号过长(最多 50 字符)")
|
||||
continue
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(row.Email))
|
||||
if email == "" {
|
||||
if strings.TrimSpace(fallbackDomain) == "" {
|
||||
fail("邮箱为空且系统未配置兜底邮箱域,无法合成占位邮箱")
|
||||
continue
|
||||
}
|
||||
email = synthesizeImportEmail(row.EmployeeNo, fallbackDomain)
|
||||
}
|
||||
if !isValidImportEmail(email) {
|
||||
fail("邮箱格式不正确")
|
||||
continue
|
||||
}
|
||||
res.Email = email
|
||||
role, roleOK := parseMemberImportRole(row.RoleRaw)
|
||||
if !roleOK {
|
||||
fail("角色必须是 owner / admin / contributor / viewer(或 所有者 / 管理员 / 编辑 / 访客)")
|
||||
continue
|
||||
}
|
||||
|
||||
// --- 文件内去重(校验通过后才登记,坏行不占用身份键) ------------
|
||||
identityKeys := []string{email, strings.ToLower(row.EmployeeNo)}
|
||||
duplicated := false
|
||||
for _, key := range identityKeys {
|
||||
if seenIdentities[key] {
|
||||
duplicated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if duplicated {
|
||||
fail("文件内重复:工号或邮箱与前面的行相同")
|
||||
continue
|
||||
}
|
||||
|
||||
// --- 匹配已有账号:邮箱优先,工号兜底 ----------------------------
|
||||
user, err := h.lookupImportUser(ctx, email, row.EmployeeNo)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "ImportMembers user lookup failed: row=%d err=%v", row.Row, err)
|
||||
fail("查询用户失败")
|
||||
continue
|
||||
}
|
||||
// 部门列自动匹配部门管理(未命中留空、不告警、不阻断导入)。
|
||||
deptMatch := deptMatcher.match(row.Dept)
|
||||
|
||||
if user != nil {
|
||||
// 老账号缺姓名时用花名册回填;部门命中时回写所属部门
|
||||
// (000156 同步态字段口径)。失败只告警,不阻断该行导入。
|
||||
dirty := false
|
||||
if user.DisplayName == "" && strings.TrimSpace(row.Name) != "" {
|
||||
user.DisplayName = strings.TrimSpace(row.Name)
|
||||
dirty = true
|
||||
}
|
||||
if deptMatch != nil && (user.DeptName != deptMatch.Name || user.DeptCode != deptMatch.Code) {
|
||||
user.DeptName = deptMatch.Name
|
||||
user.DeptCode = deptMatch.Code
|
||||
dirty = true
|
||||
}
|
||||
if dirty {
|
||||
user.UpdatedAt = time.Now()
|
||||
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
|
||||
logger.Warnf(ctx, "ImportMembers: profile backfill failed: user=%s err=%v",
|
||||
user.ID, updateErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 自动开户(与 provisionOIDCUser 同模式) ----------------------
|
||||
createdAccount := false
|
||||
if user == nil {
|
||||
newUser, createErr := h.createImportUser(ctx, row.EmployeeNo, email, row.Name, deptMatch)
|
||||
if createErr == nil {
|
||||
user = newUser
|
||||
createdAccount = true
|
||||
} else if errors.Is(createErr, service.ErrUserEmailExists) ||
|
||||
errors.Is(createErr, service.ErrUserUsernameExists) {
|
||||
// 唯一键竞态(邮箱/工号在处理途中被并发注册占用)→ 回退重查,
|
||||
// 命中已有账号时按普通「加入」处理(createdAccount 保持 false)。
|
||||
user, err = h.lookupImportUser(ctx, email, row.EmployeeNo)
|
||||
if err != nil || user == nil {
|
||||
logger.Errorf(ctx, "ImportMembers user lookup after create race failed: row=%d employee_no=%s err=%v",
|
||||
row.Row, secutils.SanitizeForLog(row.EmployeeNo), err)
|
||||
fail("账号创建失败:" + createErr.Error())
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
logger.Errorf(ctx, "ImportMembers create user failed: row=%d employee_no=%s err=%v",
|
||||
row.Row, secutils.SanitizeForLog(row.EmployeeNo), createErr)
|
||||
fail("账号创建失败:" + createErr.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
seenIdentities[email] = true
|
||||
seenIdentities[strings.ToLower(row.EmployeeNo)] = true
|
||||
|
||||
if seenUserIDs[user.ID] {
|
||||
fail("文件内重复:工号或邮箱与前面的行相同")
|
||||
continue
|
||||
}
|
||||
seenUserIDs[user.ID] = true
|
||||
|
||||
// --- 加入空间(直加路径;AddMember 自带 rbac.member_added 审计) --
|
||||
_, err = h.memberService.AddMember(ctx, user.ID, tenantID, role, invitedBy)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrMembershipAlreadyExists) {
|
||||
res.Status = "exists"
|
||||
res.Reason = "已是空间成员"
|
||||
results = append(results, res)
|
||||
exists++
|
||||
continue
|
||||
}
|
||||
logger.Errorf(ctx, "ImportMembers AddMember failed: row=%d user=%s tenant=%d err=%v",
|
||||
row.Row, user.ID, tenantID, err)
|
||||
fail("加入空间失败:" + err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
// 无归属空间的账号(含本次新建)收编为该空间默认空间,
|
||||
// 首次登录即落在正确的工作区(与 auto-accept 邀请路径一致)。
|
||||
// 失败只告警:成员关系已写入,登录路径的成员检查会兜底。
|
||||
if user.TenantID == 0 {
|
||||
user.TenantID = tenantID
|
||||
user.UpdatedAt = time.Now()
|
||||
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
|
||||
logger.Warnf(ctx, "ImportMembers: member added but default tenant update failed: user=%s tenant=%d err=%v",
|
||||
user.ID, tenantID, updateErr)
|
||||
}
|
||||
}
|
||||
|
||||
if createdAccount {
|
||||
res.Status = "created"
|
||||
created++
|
||||
} else {
|
||||
res.Status = "added"
|
||||
}
|
||||
added++
|
||||
results = append(results, res)
|
||||
}
|
||||
return results, added, created, exists, failed
|
||||
}
|
||||
|
||||
// lookupImportUser 按邮箱、再按工号(users.username)查找已有账号;
|
||||
// 未命中返回 (nil, nil),查询故障返回 error。
|
||||
func (h *TenantMemberHandler) lookupImportUser(ctx context.Context, email, employeeNo string) (*types.User, error) {
|
||||
user, err := h.userService.GetUserByEmail(ctx, email)
|
||||
if err != nil && !errors.Is(err, repository.ErrUserNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
if user != nil {
|
||||
return user, nil
|
||||
}
|
||||
user, err = h.userService.GetUserByUsername(ctx, employeeNo)
|
||||
if err != nil && !errors.Is(err, repository.ErrUserNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// createImportUser 创建本地账号:随机密码、tenantless(不建个人空间)、
|
||||
// OidcOnlyLogin 标记——与 OIDC 首登自动开户同模式,员工首次 Casdoor 登录时
|
||||
// 按邮箱命中或经 adoptOIDCUserByUsername 按工号收编,不会重复开户。
|
||||
// dept 非空时随资料初始化一并回写所属部门(省一次 UpdateUser)。
|
||||
func (h *TenantMemberHandler) createImportUser(
|
||||
ctx context.Context, employeeNo, email, name string, dept *types.OrgDept,
|
||||
) (*types.User, error) {
|
||||
password, err := randomImportPassword()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("生成初始密码失败: %w", err)
|
||||
}
|
||||
user, err := h.userService.Register(ctx, &types.RegisterRequest{
|
||||
Username: employeeNo,
|
||||
Email: email,
|
||||
Password: password,
|
||||
TenantProvisioning: types.TenantProvisioningTenantless,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if trimmed := strings.TrimSpace(name); trimmed != "" {
|
||||
user.DisplayName = trimmed
|
||||
}
|
||||
if dept != nil {
|
||||
user.DeptName = dept.Name
|
||||
user.DeptCode = dept.Code
|
||||
}
|
||||
oidcOnly := true
|
||||
user.Preferences.OidcOnlyLogin = &oidcOnly
|
||||
user.UpdatedAt = time.Now()
|
||||
if err := h.userService.UpdateUser(ctx, user); err != nil {
|
||||
return nil, fmt.Errorf("标记 OIDC-only 登录偏好失败: %w", err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 部门列自动匹配(部门管理 org_depts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// memberImportDeptMatcher 本租户部门管理的内存快照,供导入逐行匹配。
|
||||
// 名称/编号双键精确命中优先;都未命中时退化为「唯一子串」命中——
|
||||
// 花名册写「研发」也能对上部门管理里的「研发部」,多个候选视为歧义
|
||||
// 不匹配(留空比错配安全)。
|
||||
type memberImportDeptMatcher struct {
|
||||
all []*types.OrgDept
|
||||
byName map[string]*types.OrgDept // 小写名称 → 部门(首见优先,与列表序一致)
|
||||
byCode map[string]*types.OrgDept // 小写编号 → 部门
|
||||
}
|
||||
|
||||
// loadImportDeptMatcher 快照本租户部门树。部门管理服务缺失或查询失败时
|
||||
// 返回 nil——部门列整列忽略(导入主流程是加人,部门匹配只是增强,
|
||||
// 与 Casdoor 同步「无部门数据降级为纯成员同步」同思路)。
|
||||
func (h *TenantMemberHandler) loadImportDeptMatcher(ctx context.Context, tenantID uint64) *memberImportDeptMatcher {
|
||||
if h.orgService == nil {
|
||||
return nil
|
||||
}
|
||||
depts, err := h.orgService.ListDepts(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "ImportMembers list depts failed (dept matching degraded): tenant=%d err=%v",
|
||||
tenantID, err)
|
||||
return nil
|
||||
}
|
||||
m := &memberImportDeptMatcher{
|
||||
all: make([]*types.OrgDept, 0, len(depts)),
|
||||
byName: make(map[string]*types.OrgDept, len(depts)),
|
||||
byCode: make(map[string]*types.OrgDept, len(depts)),
|
||||
}
|
||||
for _, d := range depts {
|
||||
if d == nil {
|
||||
continue
|
||||
}
|
||||
m.all = append(m.all, d)
|
||||
if name := strings.ToLower(strings.TrimSpace(d.Name)); name != "" {
|
||||
if _, exists := m.byName[name]; !exists {
|
||||
m.byName[name] = d
|
||||
}
|
||||
}
|
||||
if code := strings.ToLower(strings.TrimSpace(d.Code)); code != "" {
|
||||
m.byCode[code] = d
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// match 返回输入部门对应的部门管理条目;nil 表示未匹配(留空)。
|
||||
func (m *memberImportDeptMatcher) match(raw string) *types.OrgDept {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
v := strings.ToLower(strings.TrimSpace(raw))
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
if d, ok := m.byName[v]; ok {
|
||||
return d
|
||||
}
|
||||
if d, ok := m.byCode[v]; ok {
|
||||
return d
|
||||
}
|
||||
// 唯一子串兜底:输入是某部门名称的子串且只命中一个部门时采用。
|
||||
var hits []*types.OrgDept
|
||||
for _, d := range m.all {
|
||||
name := strings.ToLower(strings.TrimSpace(d.Name))
|
||||
if name != "" && name != v && strings.Contains(name, v) {
|
||||
hits = append(hits, d)
|
||||
if len(hits) > 1 {
|
||||
return nil // 多候选歧义,放弃匹配
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(hits) == 1 {
|
||||
return hits[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Excel 解析
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// parseMemberImportExcel 解析成员导入 Excel:在所有工作表中探测表头
|
||||
// (须同时含「工号」与「邮箱」列),返回数据行。
|
||||
func parseMemberImportExcel(data []byte) ([]memberImportRow, error) {
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, apperrors.NewValidationError("Excel 文件解析失败").WithDetails(err.Error())
|
||||
}
|
||||
defer f.Close()
|
||||
for _, sheet := range f.GetSheetList() {
|
||||
rows, err := f.GetRows(sheet)
|
||||
if err != nil || len(rows) == 0 {
|
||||
continue
|
||||
}
|
||||
headerIdx, cols, ok := detectMemberImportHeader(rows)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out := make([]memberImportRow, 0, len(rows)-headerIdx-1)
|
||||
for i := headerIdx + 1; i < len(rows); i++ {
|
||||
cells := rows[i]
|
||||
cell := func(idx int) string {
|
||||
if idx < 0 || idx >= len(cells) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(cells[idx])
|
||||
}
|
||||
r := memberImportRow{
|
||||
Row: i + 1,
|
||||
EmployeeNo: cell(cols.employeeNo),
|
||||
Email: cell(cols.email),
|
||||
Name: cell(cols.name),
|
||||
Dept: cell(cols.dept),
|
||||
RoleRaw: cell(cols.role),
|
||||
}
|
||||
// 整行全空跳过,不计入结果。
|
||||
if r.EmployeeNo == "" && r.Email == "" && r.Name == "" && r.Dept == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, apperrors.NewValidationError("Excel 中没有可导入的数据行")
|
||||
}
|
||||
if len(out) > memberImportMaxRows {
|
||||
return nil, apperrors.NewValidationError(
|
||||
fmt.Sprintf("单次最多导入 %d 行,当前文件有 %d 行", memberImportMaxRows, len(out)))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
return nil, apperrors.NewValidationError("未识别到模板表头(需同时包含「工号」与「邮箱」列,可先下载模板)")
|
||||
}
|
||||
|
||||
// detectMemberImportHeader 在前 N 行内探测表头行,返回行下标与列映射。
|
||||
func detectMemberImportHeader(rows [][]string) (int, *memberImportColumns, bool) {
|
||||
scan := len(rows)
|
||||
if scan > memberImportHeaderScanRows {
|
||||
scan = memberImportHeaderScanRows
|
||||
}
|
||||
for i := 0; i < scan; i++ {
|
||||
cols := mapMemberImportHeader(rows[i])
|
||||
if cols.employeeNo >= 0 && cols.email >= 0 {
|
||||
return i, cols, true
|
||||
}
|
||||
}
|
||||
return 0, nil, false
|
||||
}
|
||||
|
||||
// mapMemberImportHeader 按列名子串容错映射(兼容「员工工号」「所属部门」「Email 地址」等写法)。
|
||||
func mapMemberImportHeader(cells []string) *memberImportColumns {
|
||||
cols := memberImportColumns{employeeNo: -1, email: -1, name: -1, dept: -1, role: -1}
|
||||
limit := len(cells)
|
||||
if limit > memberImportMaxHeaderCols {
|
||||
limit = memberImportMaxHeaderCols
|
||||
}
|
||||
for idx := 0; idx < limit; idx++ {
|
||||
v := strings.ToLower(strings.TrimSpace(cells[idx]))
|
||||
switch {
|
||||
case cols.employeeNo < 0 && (strings.Contains(v, "工号") || strings.Contains(v, "employee")):
|
||||
cols.employeeNo = idx
|
||||
case cols.email < 0 && (strings.Contains(v, "邮箱") || strings.Contains(v, "mail")):
|
||||
cols.email = idx
|
||||
case cols.name < 0 && (strings.Contains(v, "姓名") || strings.Contains(v, "名字") || v == "name"):
|
||||
cols.name = idx
|
||||
case cols.dept < 0 && (strings.Contains(v, "部门") || strings.Contains(v, "dept")):
|
||||
cols.dept = idx
|
||||
case cols.role < 0 && (strings.Contains(v, "角色") || v == "role"):
|
||||
cols.role = idx
|
||||
}
|
||||
}
|
||||
return &cols
|
||||
}
|
||||
|
||||
// parseMemberImportRole 角色列取值:英文键或中文标签(与前端 roleOptions 文案对齐);
|
||||
// 空值默认访客(viewer)。
|
||||
func parseMemberImportRole(raw string) (types.TenantRole, bool) {
|
||||
switch strings.TrimSpace(raw) {
|
||||
case "", "viewer", "访客":
|
||||
return types.TenantRoleViewer, true
|
||||
case "owner", "所有者":
|
||||
return types.TenantRoleOwner, true
|
||||
case "admin", "管理员":
|
||||
return types.TenantRoleAdmin, true
|
||||
case "contributor", "编辑", "贡献者":
|
||||
return types.TenantRoleContributor, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// synthesizeImportEmail 邮箱缺失时合成 <工号>@<兜底域> 占位地址,
|
||||
// 与 service 层 synthesizeOIDCEmail 同规则(合成邮箱是永久查询键,确定性优先)。
|
||||
func synthesizeImportEmail(employeeNo, fallbackDomain string) string {
|
||||
local := sanitizeImportEmailLocalPart(employeeNo)
|
||||
if local == "" {
|
||||
return ""
|
||||
}
|
||||
return local + "@" + strings.TrimPrefix(strings.TrimSpace(fallbackDomain), "@")
|
||||
}
|
||||
|
||||
// sanitizeImportEmailLocalPart 只保留 email local part 的安全字符,
|
||||
// 其余折叠为下划线并截断到 64 字符(与 synthesizeOIDCEmail 的清洗一致)。
|
||||
func sanitizeImportEmailLocalPart(value string) string {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
var b strings.Builder
|
||||
for _, r := range value {
|
||||
if b.Len() >= 64 {
|
||||
break
|
||||
}
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "._-")
|
||||
}
|
||||
|
||||
// isValidImportEmail 轻量校验:本地部分非空、有 @、域内有点、无空白。
|
||||
func isValidImportEmail(email string) bool {
|
||||
at := strings.Index(email, "@")
|
||||
return at > 0 &&
|
||||
at < len(email)-1 &&
|
||||
!strings.ContainsAny(email, " \t") &&
|
||||
strings.Contains(email[at+1:], ".")
|
||||
}
|
||||
|
||||
// randomImportPassword 生成随机初始密码。导入开户的用户不会用该密码登录
|
||||
// (OIDC-only),与 provisionOIDCUser 的 32 字节随机口令同强度。
|
||||
func randomImportPassword() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// readAllImportBytes 读取上传文件内容(excelize.OpenReader 需要 io.Reader,
|
||||
// 这里一次性读入以便统一限流与错误处理)。
|
||||
func readAllImportBytes(fh multipart.File) ([]byte, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
if _, err := buf.ReadFrom(fh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 成员批量导入:新模板(工号/姓名/部门/邮箱/角色)与部门列自动匹配。
|
||||
// 部门列在部门管理(org_depts)中按名称/编号自动匹配,未命中留空不阻断。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// TestMapMemberImportHeaderDeptColumn 新模板五列表头的下标映射。
|
||||
func TestMapMemberImportHeaderDeptColumn(t *testing.T) {
|
||||
cols := mapMemberImportHeader([]string{"工号", "姓名", "部门", "邮箱", "角色"})
|
||||
require.Equal(t, 0, cols.employeeNo)
|
||||
require.Equal(t, 1, cols.name)
|
||||
require.Equal(t, 2, cols.dept)
|
||||
require.Equal(t, 3, cols.email)
|
||||
require.Equal(t, 4, cols.role)
|
||||
|
||||
// 旧模板(无部门列)仍可解析,dept 为 -1。
|
||||
old := mapMemberImportHeader([]string{"工号", "邮箱", "姓名", "角色"})
|
||||
require.Equal(t, -1, old.dept)
|
||||
|
||||
// 兼容「所属部门」「Department」等写法。
|
||||
require.Equal(t, 1, mapMemberImportHeader([]string{"工号", "所属部门"}).dept)
|
||||
require.Equal(t, 0, mapMemberImportHeader([]string{"Department"}).dept)
|
||||
}
|
||||
|
||||
// TestParseMemberImportExcelDeptColumn 新模板 Excel 的部门列进入解析结果。
|
||||
func TestParseMemberImportExcelDeptColumn(t *testing.T) {
|
||||
f := excelize.NewFile()
|
||||
sheet := f.GetSheetName(0)
|
||||
for i, h := range []string{"工号", "姓名", "部门", "邮箱", "角色"} {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
require.NoError(t, f.SetCellValue(sheet, cell, h))
|
||||
}
|
||||
for i, v := range []interface{}{"26080007", "张三", "研发部", "26080007@example.com", "访客"} {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 2)
|
||||
require.NoError(t, f.SetCellValue(sheet, cell, v))
|
||||
}
|
||||
buf, err := f.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
|
||||
rows, err := parseMemberImportExcel(buf.Bytes())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, "26080007", rows[0].EmployeeNo)
|
||||
require.Equal(t, "张三", rows[0].Name)
|
||||
require.Equal(t, "研发部", rows[0].Dept)
|
||||
require.Equal(t, "26080007@example.com", rows[0].Email)
|
||||
require.Equal(t, "访客", rows[0].RoleRaw)
|
||||
}
|
||||
|
||||
// TestMemberImportDeptMatcher 部门匹配语义:名称/编号精确命中、唯一子串
|
||||
// 兜底、多候选歧义放弃、空白输入与 nil 匹配器安全返回。
|
||||
func TestMemberImportDeptMatcher(t *testing.T) {
|
||||
rd := &types.OrgDept{ID: "d1", Name: "研发部", Code: "RD"}
|
||||
mk := &types.OrgDept{ID: "d2", Name: "市场部", Code: "MK"}
|
||||
m := &memberImportDeptMatcher{
|
||||
all: []*types.OrgDept{rd, mk},
|
||||
byName: map[string]*types.OrgDept{"研发部": rd, "市场部": mk},
|
||||
byCode: map[string]*types.OrgDept{"rd": rd, "mk": mk},
|
||||
}
|
||||
|
||||
require.Same(t, rd, m.match("研发部"))
|
||||
require.Same(t, rd, m.match(" 研发部 ")) // 首尾空白容忍
|
||||
require.Same(t, rd, m.match("RD")) // 编号命中(大小写无关)
|
||||
require.Same(t, mk, m.match("市场部"))
|
||||
require.Same(t, rd, m.match("研发")) // 唯一子串兜底
|
||||
require.Nil(t, m.match("部")) // 多候选歧义 → 不匹配
|
||||
require.Nil(t, m.match("财务部")) // 无命中
|
||||
require.Nil(t, m.match("")) // 空输入
|
||||
require.Nil(t, m.match(" "))
|
||||
var nilMatcher *memberImportDeptMatcher
|
||||
require.Nil(t, nilMatcher.match("研发部")) // 降级形态:整列忽略
|
||||
}
|
||||
|
||||
// stubImportUserService 只实现导入链路触达的用户方法(查询/开户/更新)。
|
||||
type stubImportUserService struct {
|
||||
interfaces.UserService
|
||||
byEmail map[string]*types.User
|
||||
byUsername map[string]*types.User
|
||||
created []*types.User
|
||||
updated []*types.User
|
||||
}
|
||||
|
||||
func (s *stubImportUserService) GetUserByEmail(_ context.Context, email string) (*types.User, error) {
|
||||
return s.byEmail[strings.ToLower(email)], nil
|
||||
}
|
||||
|
||||
func (s *stubImportUserService) GetUserByUsername(_ context.Context, username string) (*types.User, error) {
|
||||
return s.byUsername[username], nil
|
||||
}
|
||||
|
||||
func (s *stubImportUserService) Register(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
u := &types.User{ID: "u-" + req.Username, Username: req.Username, Email: req.Email}
|
||||
s.created = append(s.created, u)
|
||||
s.byUsername[req.Username] = u
|
||||
s.byEmail[strings.ToLower(req.Email)] = u
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *stubImportUserService) UpdateUser(_ context.Context, u *types.User) error {
|
||||
s.updated = append(s.updated, u)
|
||||
return nil
|
||||
}
|
||||
|
||||
// stubImportOrgService 只提供部门树快照。
|
||||
type stubImportOrgService struct {
|
||||
interfaces.OrgCenterService
|
||||
depts []*types.OrgDept
|
||||
}
|
||||
|
||||
func (s *stubImportOrgService) ListDepts(_ context.Context, _ uint64) ([]*types.OrgDept, error) {
|
||||
return s.depts, nil
|
||||
}
|
||||
|
||||
// TestProcessMemberImportRowsDeptMatching 端到端:新建账号与老账号均回写
|
||||
// 匹配到的部门,未命中部门留空且不阻断导入。
|
||||
func TestProcessMemberImportRowsDeptMatching(t *testing.T) {
|
||||
rd := &types.OrgDept{ID: "d1", Name: "研发部", Code: "RD"}
|
||||
us := &stubImportUserService{
|
||||
byEmail: map[string]*types.User{},
|
||||
byUsername: map[string]*types.User{},
|
||||
}
|
||||
// 老账号:缺姓名、无部门,按邮箱命中。
|
||||
us.byEmail["old@example.com"] = &types.User{ID: "u-old", Email: "old@example.com"}
|
||||
|
||||
h := NewTenantMemberHandler(
|
||||
&stubMemberService{add: func(_ context.Context, _ string, _ uint64, _ types.TenantRole, _ *string) (*types.TenantMember, error) {
|
||||
return &types.TenantMember{}, nil
|
||||
}},
|
||||
us,
|
||||
&stubImportOrgService{depts: []*types.OrgDept{rd}},
|
||||
nil, nil,
|
||||
)
|
||||
|
||||
rows := []memberImportRow{
|
||||
{Row: 2, EmployeeNo: "26080007", Email: "new@example.com", Name: "张三", Dept: "研发部"},
|
||||
{Row: 3, EmployeeNo: "0107004", Email: "old@example.com", Dept: "研发"}, // 子串命中 + 老账号
|
||||
{Row: 4, EmployeeNo: "26080008", Email: "nomatch@example.com", Dept: "不存在的部门"},
|
||||
{Row: 5, EmployeeNo: "26080009", Email: "nodept@example.com"}, // 部门列留空
|
||||
}
|
||||
results, added, created, exists, failed := h.processMemberImportRows(
|
||||
context.Background(), 1, rows, h.loadImportDeptMatcher(context.Background(), 1),
|
||||
"casdoor.local", nil)
|
||||
|
||||
require.Len(t, results, 4)
|
||||
require.Equal(t, 4, added)
|
||||
require.Equal(t, 3, created) // 行 2/4/5 未命中已有账号 → 自动开户
|
||||
require.Equal(t, 0, exists)
|
||||
require.Equal(t, 0, failed)
|
||||
|
||||
// 新建账号:部门随资料初始化一并写入。
|
||||
var zhang *types.User
|
||||
for _, u := range us.created {
|
||||
if u.Username == "26080007" {
|
||||
zhang = u
|
||||
}
|
||||
}
|
||||
require.NotNil(t, zhang)
|
||||
require.Equal(t, "研发部", zhang.DeptName)
|
||||
require.Equal(t, "RD", zhang.DeptCode)
|
||||
|
||||
// 老账号:命中子串「研发」→ 回填部门。
|
||||
old := us.byEmail["old@example.com"]
|
||||
require.Equal(t, "研发部", old.DeptName)
|
||||
require.Equal(t, "RD", old.DeptCode)
|
||||
|
||||
// 未命中部门的行:账号照常导入,部门留空。
|
||||
nomatch := us.byUsername["26080008"]
|
||||
require.NotNil(t, nomatch)
|
||||
require.Empty(t, nomatch.DeptName)
|
||||
require.Empty(t, nomatch.DeptCode)
|
||||
|
||||
// 部门列缺失的行:正常导入。
|
||||
require.NotNil(t, us.byUsername["26080009"])
|
||||
}
|
||||
|
||||
// TestProcessMemberImportRowsDeptDegraded 部门管理不可用(匹配器为 nil)时
|
||||
// 部门列整列忽略,导入不受影响。
|
||||
func TestProcessMemberImportRowsDeptDegraded(t *testing.T) {
|
||||
us := &stubImportUserService{
|
||||
byEmail: map[string]*types.User{},
|
||||
byUsername: map[string]*types.User{},
|
||||
}
|
||||
h := NewTenantMemberHandler(
|
||||
&stubMemberService{add: func(_ context.Context, _ string, _ uint64, _ types.TenantRole, _ *string) (*types.TenantMember, error) {
|
||||
return &types.TenantMember{}, nil
|
||||
}},
|
||||
us, nil, nil, nil, // orgService 缺失
|
||||
)
|
||||
|
||||
rows := []memberImportRow{
|
||||
{Row: 2, EmployeeNo: "26080007", Email: "a@example.com", Dept: "研发部"},
|
||||
}
|
||||
_, added, created, _, failed := h.processMemberImportRows(
|
||||
context.Background(), 1, rows, nil, "casdoor.local", nil)
|
||||
|
||||
require.Equal(t, 1, added)
|
||||
require.Equal(t, 1, created)
|
||||
require.Zero(t, failed)
|
||||
createdUser := us.byUsername["26080007"]
|
||||
require.NotNil(t, createdUser)
|
||||
require.Empty(t, createdUser.DeptName)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
apperrors "academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 同步CASDOOR成员(设置 → 成员管理 → 同步CASDOOR成员,000156):
|
||||
// 与批量导入并列的直加路径——后端经 Casdoor 管理 API(client_credentials)
|
||||
// 拉全量用户目录,自动开户并以 viewer 加入当前空间;部门编号/名称随账号
|
||||
// 回写(users.dept_code/dept_name)并对齐组织架构 org_depts。
|
||||
// 单向增量幂等:不删除、不停用、不改已有成员角色。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// SyncCasdoorMembers godoc
|
||||
// @Summary 同步 CASDOOR 成员到当前空间
|
||||
// @Description
|
||||
//
|
||||
// Owner 触发一次 Casdoor 用户目录同步:经管理 API 拉全量用户,
|
||||
// 未注册的自动创建本地账号(随机密码、OIDC-only,首次登录自动收编),
|
||||
// 非成员以观察者(viewer)加入当前空间;已有成员保持角色不变。
|
||||
// Casdoor 用户带部门数据时,同步组织架构部门(org_depts)并回写
|
||||
// 账号的部门编号/名称,供成员列表「所属部门」列与「从平台用户添加」
|
||||
// 自动带部门使用。逐条容错,响应返回汇总与跳过明细。
|
||||
// 前置:OIDC_AUTH_ADMIN_API_ENABLE=true 且 Casdoor 应用已开启
|
||||
// Client Credentials 授权。
|
||||
//
|
||||
// @Tags 空间成员
|
||||
// @Produce json
|
||||
// @Param id path string true "空间 ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /tenants/{id}/members/sync-casdoor [post]
|
||||
func (h *TenantMemberHandler) SyncCasdoorMembers(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID, ok := parseTenantIDFromPath(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if h.syncService == nil {
|
||||
c.Error(apperrors.NewBadRequestError("同步功能未装配(Casdoor 管理客户端初始化失败)"))
|
||||
return
|
||||
}
|
||||
|
||||
// 归因到人类调用者(合成主体不留 invited_by,与 AddMember 同规则)。
|
||||
operator, _ := types.UserIDFromContext(ctx)
|
||||
|
||||
result, err := h.syncService.SyncMembers(ctx, tenantID, operator)
|
||||
if err != nil {
|
||||
// 错误文案面向操作者(未启用/授权未开/权限不足/拉取失败),
|
||||
// 以 400 回传原文,前端提示可直接展示。
|
||||
logger.Errorf(ctx, "SyncCasdoorMembers failed: tenant=%d operator=%s err=%v",
|
||||
tenantID, secutils.SanitizeForLog(operator), err)
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "SyncCasdoorMembers done: tenant=%d operator=%s casdoor_total=%d users_created=%d members_added=%d members_existing=%d depts_created=%d skipped=%d",
|
||||
tenantID, secutils.SanitizeForLog(operator), result.Total, result.UsersCreated,
|
||||
result.MembersAdded, result.MembersExist, result.DeptsCreated, len(result.Skipped))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": result,
|
||||
})
|
||||
}
|
||||
@@ -126,7 +126,9 @@ func (s *stubMemberUserService) GetUsersByIDs(ctx context.Context, ids []string)
|
||||
// middleware via memberTestRouter rather than threading a cfg through
|
||||
// the handler.
|
||||
func newTestMemberHandler(ms interfaces.TenantMemberService, us interfaces.UserService) *TenantMemberHandler {
|
||||
return NewTenantMemberHandler(ms, us)
|
||||
// 组织中心/同步服务传 nil:CRUD 测试不触达部门匹配与 sync-casdoor
|
||||
// 路由(handler 内均有 nil 兜底)。
|
||||
return NewTenantMemberHandler(ms, us, nil, nil, nil)
|
||||
}
|
||||
|
||||
// memberTestRouter wires the handler with the same errorCapture middleware
|
||||
@@ -685,7 +687,7 @@ func TestTenantMember_SuperuserBypassRequiresFeatureFlag(t *testing.T) {
|
||||
// Build the router with the flag explicitly off — the carve-out
|
||||
// now lives in middleware.RequirePathTenantMatch, which the router
|
||||
// helper mounts.
|
||||
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
|
||||
h := NewTenantMemberHandler(ms, &stubMemberUserService{}, nil, nil, nil)
|
||||
router := memberTestRouterWithCfg(h, &config.Config{
|
||||
Tenant: &config.TenantConfig{EnableCrossTenantAccess: false},
|
||||
})
|
||||
|
||||
@@ -32,12 +32,41 @@ func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotifi
|
||||
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 {
|
||||
if v := c.GetUint64(trainingTenantContextKey); v != 0 {
|
||||
return v
|
||||
}
|
||||
return c.GetUint64(types.TenantIDContextKey.String())
|
||||
}
|
||||
|
||||
@@ -180,6 +209,32 @@ func (h *Handler) callerDeptScope(c *gin.Context) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// callerCourseLibraryScope 课程管理列表的数据范围(000157):人事/空间管理员全局
|
||||
// (两个返回值均空);课长/经理限本部门(owner_dept_id);讲师/学员(无维护角色)
|
||||
// 收窄为「与我相关」——自己创建或自己授课的课程。relatedUserID 非空时 repo 按
|
||||
// creator_id/lecturer_id 过滤。
|
||||
func (h *Handler) callerCourseLibraryScope(c *gin.Context) (deptID, relatedUserID string) {
|
||||
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
|
||||
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
|
||||
return "", ""
|
||||
}
|
||||
userID := callerUserID(c)
|
||||
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), userID)
|
||||
if err != nil || member == nil {
|
||||
return "", userID
|
||||
}
|
||||
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
|
||||
switch {
|
||||
case types.HasTrainingRole(roles, types.TrainingRoleHR):
|
||||
return "", ""
|
||||
case types.HasTrainingRole(roles, types.TrainingRoleSupervisor):
|
||||
// 经理继承课长权限组,与课长一致收窄本部门
|
||||
return member.DeptID, ""
|
||||
default:
|
||||
return "", userID
|
||||
}
|
||||
}
|
||||
|
||||
// checkCourseVisibility 课程详情可见性:全局视角与已发布课程对所有人开放;
|
||||
// 纯讲师另可见自己相关的未发布课程(供维护);纯学员不可见未发布课程。
|
||||
func (h *Handler) checkCourseVisibility(c *gin.Context, course *types.TrainingCourse) error {
|
||||
@@ -374,6 +429,18 @@ func (h *Handler) Me(c *gin.Context) {
|
||||
_ = c.Error(err)
|
||||
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})
|
||||
}
|
||||
|
||||
@@ -410,9 +477,12 @@ func (h *Handler) ListDemandYears(c *gin.Context) {
|
||||
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
|
||||
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
|
||||
type saveDemandRequest struct {
|
||||
ID string `json:"id"`
|
||||
Year int `json:"year"`
|
||||
DeptID string `json:"dept_id"`
|
||||
ID string `json:"id"`
|
||||
Year int `json:"year"`
|
||||
DeptID string `json:"dept_id"`
|
||||
// DeptName Excel「部门」列原始值(仅批量导入部门归属校验用,000158:全部行
|
||||
// 必须为导入人本人部门;在线提报不传,服务端强制按提报人部门落库)。
|
||||
DeptName string `json:"dept_name"`
|
||||
CourseName string `json:"course_name" binding:"required"`
|
||||
Plant string `json:"plant"`
|
||||
Category string `json:"category"`
|
||||
@@ -478,14 +548,23 @@ func (h *Handler) SaveDemand(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。
|
||||
deptID := trimSpace(req.DeptID)
|
||||
if deptID == "" {
|
||||
if existing != nil {
|
||||
deptID = existing.DeptID
|
||||
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil {
|
||||
deptID = member.DeptID
|
||||
// 部门口径(000158):所属部门必须为填报人本人部门——新建强制按提报人所在
|
||||
// 部门(org_employees.dept_id)落库,忽略请求值防绕过;编辑保留原部门(人事
|
||||
// 代改也不覆盖归属)。提报人无部门档案时阻断,先由人事在组织中心维护。
|
||||
var deptID string
|
||||
if existing != nil {
|
||||
deptID = existing.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{
|
||||
ID: req.ID, Year: req.Year, DeptID: deptID,
|
||||
@@ -549,6 +628,9 @@ func (h *Handler) ListPosts(c *gin.Context) {
|
||||
}
|
||||
|
||||
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。
|
||||
// 部门口径(000158):全部行必须为导入人本人部门(org_employees.dept_id,全员
|
||||
// 严格,人事也不例外);部门列留空视为默认导入人部门,其余任一行不符即整批
|
||||
// 拒绝。导入人无部门档案时阻断,先由人事在组织中心维护。
|
||||
func (h *Handler) ImportDemands(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
@@ -561,10 +643,47 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
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))
|
||||
for _, item := range req.Demands {
|
||||
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,
|
||||
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
|
||||
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
|
||||
@@ -572,16 +691,34 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
||||
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 {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
|
||||
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
|
||||
h.syncDemandLecturerToLibrary(ctx, tenantID, userID, demands)
|
||||
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
|
||||
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}})
|
||||
notified := h.notifyDemandVerify(ctx, tenantID, demands)
|
||||
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 权限收窄):
|
||||
@@ -655,10 +792,13 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
|
||||
PostScope: demand.PostScope,
|
||||
}
|
||||
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
|
||||
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
|
||||
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
|
||||
// 课程管理关联(000158):需求填报/导入时已按名称精准匹配并回填
|
||||
// library_course_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 {
|
||||
if item != nil && item.Name == demand.CourseName {
|
||||
course.LibraryCourseID = item.ID
|
||||
@@ -875,47 +1015,75 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
|
||||
}
|
||||
}
|
||||
|
||||
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
|
||||
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
|
||||
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
|
||||
// syncDemandLecturerToLibrary 需求课程信息回写课程管理(000156/000161):需求
|
||||
// (导入/在线保存/编辑)所关联的课程管理条目——优先 demand.library_course_id
|
||||
// (000158 自动匹配),无值回退同名匹配——讲师与条目不一致时以需求为准更新;
|
||||
// 000161 扩展:分类/适合人员(需求侧改后)同样回写。SaveCourseLibraryItem 的
|
||||
// 编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须重新签核。
|
||||
// 同批同名取首条。fail-open:失败仅记日志不阻断保存/导入。
|
||||
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
|
||||
byID := map[string]*types.TrainingDemand{}
|
||||
byName := map[string]*types.TrainingDemand{}
|
||||
for _, d := range demands {
|
||||
if d == nil || trimSpace(d.CourseName) == "" {
|
||||
continue
|
||||
}
|
||||
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" {
|
||||
if id := trimSpace(d.LibraryCourseID); id != "" {
|
||||
if _, ok := byID[id]; !ok {
|
||||
byID[id] = d
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, ok := byName[d.CourseName]; !ok {
|
||||
byName[d.CourseName] = d
|
||||
}
|
||||
}
|
||||
if len(byName) == 0 {
|
||||
if len(byID) == 0 && len(byName) == 0 {
|
||||
return
|
||||
}
|
||||
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to list course library for lecturer sync", err)
|
||||
logger.Error(ctx, "Failed to list course library for demand sync", err)
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
d, ok := byName[item.Name]
|
||||
d, ok := byID[item.ID]
|
||||
if !ok {
|
||||
d, ok = byName[item.Name]
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
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
|
||||
}
|
||||
updated := *item
|
||||
updated.LecturerID = lecturerID
|
||||
updated.LecturerExternal = lecturerExt
|
||||
if hasLecturer {
|
||||
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 {
|
||||
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
|
||||
}
|
||||
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
|
||||
@@ -1195,26 +1363,8 @@ func (h *Handler) PublishCourse(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。
|
||||
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
|
||||
}
|
||||
// 发布前置校验(线上课件/线下讲师等)统一收口在 service PublishCourse:
|
||||
// 线上课件认计划自带或课程管理自带课件,考题非必填。
|
||||
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
@@ -1638,6 +1788,12 @@ type CheckinRequest struct {
|
||||
Channel string `json:"channel"`
|
||||
// MemberID 可选:讲师/课长/人事现场代扫码/补录。
|
||||
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 — 学员扫码签到(带定位校验);
|
||||
@@ -1661,7 +1817,15 @@ func (h *Handler) Checkin(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
|
||||
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 {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
@@ -1669,6 +1833,91 @@ func (h *Handler) Checkin(c *gin.Context) {
|
||||
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 — 签到明细。
|
||||
func (h *Handler) ListSignRecords(c *gin.Context) {
|
||||
items, err := h.svc.ListSignRecords(c.Request.Context(), callerTenantID(c), c.Param("id"))
|
||||
|
||||
@@ -17,7 +17,9 @@ import (
|
||||
// 字段:课程名称/所属部门(org_depts)/说明/适合人员/分类(配置中心
|
||||
// course_category_dict 可配,可自定义)/类型(必修课/选修课)/线上或线下/
|
||||
// 讲师/时长/课件。月培训计划的「计划名称」从本表选择。
|
||||
// 列表 Viewer 可读(月培训计划下拉同源);维护动作限人事/课长/讲师。
|
||||
// 列表 Viewer 可读(月培训计划下拉同源),数据范围按角色收窄(000157):
|
||||
// 人事全部/课长经理本部门/讲师学员仅「与我相关」;维护(新增/编辑/发布/导入/
|
||||
// 导出)限人事/课长/讲师;核验/删除仅课长/经理且限本部门、删除仅限待核验行。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// saveCourseLibraryRequest is the body of POST /training/course-library.
|
||||
@@ -62,8 +64,34 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
|
||||
}
|
||||
|
||||
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
||||
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
|
||||
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
|
||||
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方
|
||||
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护
|
||||
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
|
||||
func (h *Handler) ListCourseLibrary(c *gin.Context) {
|
||||
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), listQueryFromRequest(c))
|
||||
q := listQueryFromRequest(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)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
@@ -72,15 +100,19 @@ func (h *Handler) ListCourseLibrary(c *gin.Context) {
|
||||
}
|
||||
|
||||
// SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。
|
||||
// 维护角色限人事/课长/讲师;无维护角色的用户兜底仅可编辑「与我相关」课程
|
||||
// (本人创建或本人授课,不可新增,000157)。
|
||||
func (h *Handler) SaveCourseLibraryItem(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
var req saveCourseLibraryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
if req.ID == "" || !h.canEditRelatedLibraryCourse(c, req.ID) {
|
||||
return // requireRoles/兜底校验已写 403/404
|
||||
}
|
||||
}
|
||||
item, err := h.svc.SaveCourseLibraryItem(c.Request.Context(), callerTenantID(c), toCourseLibrary(req), callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
@@ -89,12 +121,34 @@ func (h *Handler) SaveCourseLibraryItem(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除(人事/课长)。
|
||||
// canEditRelatedLibraryCourse 无维护角色用户的编辑兜底(000157):目标课程须存在
|
||||
// 且创建人或讲师为本人;学员编辑同样触发服务层「编辑即回待核验」重核验流程。
|
||||
func (h *Handler) canEditRelatedLibraryCourse(c *gin.Context, id string) bool {
|
||||
item, err := h.svc.GetCourseLibraryItem(c.Request.Context(), callerTenantID(c), id)
|
||||
if err != nil || item == nil {
|
||||
_ = c.Error(errors.NewNotFoundError("课程不存在"))
|
||||
return false
|
||||
}
|
||||
userID := callerUserID(c)
|
||||
if item.CreatorID != userID && item.LecturerID != userID {
|
||||
_ = c.Error(errors.NewForbiddenError("仅可编辑本人创建或本人授课的课程"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除
|
||||
// (000157:仅本部门课长/经理,仅待核验状态;人事/学员/空间管理员无删除权限)。
|
||||
func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
|
||||
deptID, ok := h.callerVerifyDeptScope(c)
|
||||
if !ok {
|
||||
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可删除课程"))
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id"), deptID); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
@@ -136,6 +190,53 @@ func (h *Handler) SetCourseLibraryPublishStatus(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// callerVerifyDeptScope 核验/删除的部门口径(000157):一律按课长身份收窄本部门,
|
||||
// 不设全局旁路(人事/空间管理员均不例外)——核验权只属于「该部门课长/经理」。
|
||||
// 返回所在部门 id 与是否具备身份;无课长身份(或课长未分配部门)一律拒绝。
|
||||
func (h *Handler) callerVerifyDeptScope(c *gin.Context) (deptID string, ok bool) {
|
||||
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
|
||||
if err != nil || member == nil {
|
||||
return "", false
|
||||
}
|
||||
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
|
||||
// 经理继承课长权限组,与课长同口径;人事角色不构成核验身份。
|
||||
if types.HasTrainingRole(roles, types.TrainingRoleSupervisor) && member.DeptID != "" {
|
||||
return member.DeptID, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// verifyCourseLibraryRequest is the body of POST /training/course-library/verify
|
||||
// (单个/批量核验共用,ids 长度 1 即单条)。
|
||||
type verifyCourseLibraryRequest struct {
|
||||
IDs []string `json:"ids" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// VerifyCourseLibraryItems POST /training/course-library/verify — 课程条目核验
|
||||
// (000157):仅本部门课长/经理可核验(人事/讲师/学员/空间管理员均无跨部门核验权),
|
||||
// 待核验 → 已确认;越权/已确认/不存在行跳过不阻断其余行。
|
||||
func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) {
|
||||
return
|
||||
}
|
||||
var req verifyCourseLibraryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
deptID, ok := h.callerVerifyDeptScope(c)
|
||||
if !ok {
|
||||
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可核验课程"))
|
||||
return
|
||||
}
|
||||
verified, skipped, err := h.svc.VerifyCourseLibraryItems(c.Request.Context(), callerTenantID(c), req.IDs, callerUserID(c), deptID)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"verified": verified, "skipped": skipped}})
|
||||
}
|
||||
|
||||
// ImportCourseLibraryRequest is the body of POST /training/course-library/import
|
||||
// (前端解析 Excel 后逐行提交,与需求导入同口径)。
|
||||
type ImportCourseLibraryRequest struct {
|
||||
@@ -233,6 +334,20 @@ func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove
|
||||
// — 移除课程课件原始文件/知识库挂接(名称登记保留,课件变更即回待核验)。
|
||||
func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c))
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
|
||||
}
|
||||
|
||||
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
|
||||
// 课件原始文件流(下载/在线预览)。
|
||||
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
|
||||
|
||||
@@ -367,6 +367,18 @@ func (h *Handler) ListMyLearningTasks(c *gin.Context) {
|
||||
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= —
|
||||
// 按课程返回全员学习任务(人事/课长/讲师的「学习考试」课程学习情况视图)。
|
||||
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)
|
||||
}
|
||||
@@ -149,7 +149,7 @@ func TestCurrentWorkspaceMembersPaginationAndProjection(t *testing.T) {
|
||||
us := &stubMemberUserService{getByIDs: func(_ context.Context, _ []string) (map[string]*types.User, error) {
|
||||
return map[string]*types.User{"u1": {ID: "u1", Username: "Alice", Email: "a@example.com"}}, nil
|
||||
}}
|
||||
h := NewTenantMemberHandler(ms, us)
|
||||
h := NewTenantMemberHandler(ms, us, nil, nil, nil)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
neturl "net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -111,6 +112,65 @@ func (c *ProactiveClient) SendMarkdown(ctx context.Context, userIDs []string, co
|
||||
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.
|
||||
func (c *ProactiveClient) getAccessToken(ctx context.Context) (string, error) {
|
||||
c.tokenMu.Lock()
|
||||
|
||||
@@ -91,6 +91,12 @@ func (Backend) ClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64
|
||||
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.
|
||||
func (Backend) TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error) {
|
||||
return TenantWecomUserIDs(ctx, db, tenantID, userIDs)
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
// Package casdoor talks to the Casdoor Admin API server-side. It backs the
|
||||
// 「同步 Casdoor 成员」 flow (POST /tenants/:id/members/sync-casdoor): the
|
||||
// backend exchanges its OIDC client_id/client_secret for an access token via
|
||||
// the client_credentials grant, then pages through /api/get-users to pull the
|
||||
// IdP-side user directory.
|
||||
//
|
||||
// Prerequisites on the Casdoor side (one-time, admin console):
|
||||
// - the application's grantTypes must include "Client Credentials"
|
||||
// - the client credentials must belong to an admin-capable user/org so
|
||||
// the issued token may call the admin endpoints
|
||||
//
|
||||
// Department extraction: Casdoor keeps department info in deployment-specific
|
||||
// fields (groups tree / affiliation / title / properties map). AdminDeptField
|
||||
// / AdminDeptCodeField pin exact fields; when empty the client probes the
|
||||
// built-in candidate lists and reports which field it used, so the sync
|
||||
// result can surface the mapping to the operator.
|
||||
package casdoor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/config"
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// tokenEndpointPath is Casdoor's OAuth2 token endpoint (standard
|
||||
// /api/login/oauth/access_token; NOT /api/login, which is the SSO page
|
||||
// entry and rejects credential bodies with JSON parse errors).
|
||||
tokenEndpointPath = "/api/login/oauth/access_token"
|
||||
// listUsersPath is the admin directory endpoint.
|
||||
listUsersPath = "/api/get-users"
|
||||
// listPageSize mirrors Casdoor's default page cap for get-users.
|
||||
listPageSize = 200
|
||||
// listMaxPages safety cap: 200 * 100 = 20k users before giving up.
|
||||
listMaxPages = 100
|
||||
// requestTimeout bounds each outbound call.
|
||||
requestTimeout = 20 * time.Second
|
||||
)
|
||||
|
||||
// ErrGrantNotSupported wraps Casdoor's response when the application has not
|
||||
// enabled the client_credentials grant — the operator fix is a console toggle,
|
||||
// so callers match on this sentinel to surface actionable copy.
|
||||
var ErrGrantNotSupported = errors.New("casdoor: grant_type client_credentials is not supported in this application")
|
||||
|
||||
// ErrAdminDenied wraps 401/403 admin API responses: the token was issued but
|
||||
// lacks the privileges for /api/get-users.
|
||||
var ErrAdminDenied = errors.New("casdoor: admin api access denied")
|
||||
|
||||
// Config carries everything the admin client needs. It is a plain struct (not
|
||||
// the whole app config) so tests can construct it directly.
|
||||
type Config struct {
|
||||
BaseURL string // e.g. https://autht.well-trust.com (no trailing slash)
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
Organization string // get-users owner param; defaults to "built-in"
|
||||
DeptField string // exact field for 部门名称; empty = auto-probe
|
||||
DeptCodeField string // exact field for 部门编号; empty = auto-probe
|
||||
// Username/Password 服务账号密码模式(000156):部分 Casdoor 部署的 API 鉴权
|
||||
// (casbin) 会拒绝 client_credentials 应用令牌调 /api/get-users,此时用具备
|
||||
// 目标组织管理权限的服务账号走 password grant 换用户令牌。两者非空时优先。
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// NewConfigFromOIDC builds the admin client config from the OIDC section.
|
||||
// The base URL is derived from the explicit AdminBaseURL, else the token
|
||||
// endpoint's scheme+host, else the issuer URL.
|
||||
func NewConfigFromOIDC(oidc *config.OIDCAuthConfig) Config {
|
||||
cfg := Config{
|
||||
ClientID: oidc.ClientID,
|
||||
ClientSecret: oidc.ClientSecret,
|
||||
Organization: oidc.AdminOrganization,
|
||||
DeptField: oidc.AdminDeptField,
|
||||
DeptCodeField: oidc.AdminDeptCodeField,
|
||||
Username: oidc.AdminUsername,
|
||||
Password: oidc.AdminPassword,
|
||||
}
|
||||
switch {
|
||||
case strings.TrimSpace(oidc.AdminBaseURL) != "":
|
||||
cfg.BaseURL = strings.TrimRight(strings.TrimSpace(oidc.AdminBaseURL), "/")
|
||||
case strings.TrimSpace(oidc.TokenEndpoint) != "":
|
||||
cfg.BaseURL = baseURLFromEndpoint(oidc.TokenEndpoint)
|
||||
case strings.TrimSpace(oidc.IssuerURL) != "":
|
||||
cfg.BaseURL = strings.TrimRight(strings.TrimSpace(oidc.IssuerURL), "/")
|
||||
}
|
||||
if cfg.Organization == "" {
|
||||
cfg.Organization = "built-in"
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// baseURLFromEndpoint extracts scheme://host[:port] from an endpoint URL.
|
||||
func baseURLFromEndpoint(endpoint string) string {
|
||||
u, err := url.Parse(strings.TrimSpace(endpoint))
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return ""
|
||||
}
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
|
||||
// Client is a thin Casdoor Admin API client. The zero value is disabled.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
http *http.Client
|
||||
token string
|
||||
expiry time.Time
|
||||
}
|
||||
|
||||
// NewClient constructs the admin client from the resolved config.
|
||||
func NewClient(cfg Config) *Client {
|
||||
return &Client{
|
||||
cfg: cfg,
|
||||
http: &http.Client{
|
||||
Timeout: requestTimeout,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewClientFromOIDC builds a client from the app OIDC config; nil-safe.
|
||||
func NewClientFromOIDC(oidc *config.OIDCAuthConfig) *Client {
|
||||
if oidc == nil {
|
||||
return nil
|
||||
}
|
||||
return NewClient(NewConfigFromOIDC(oidc))
|
||||
}
|
||||
|
||||
// Enabled reports whether sync is configured at all.
|
||||
func (c *Client) Enabled() bool {
|
||||
return c != nil && c.cfg.BaseURL != "" && c.cfg.ClientID != "" && c.cfg.ClientSecret != ""
|
||||
}
|
||||
|
||||
// PasswordMode reports whether the service-account password grant is active.
|
||||
func (c *Client) PasswordMode() bool {
|
||||
return c != nil && c.cfg.Username != "" && c.cfg.Password != ""
|
||||
}
|
||||
|
||||
// Org reports the organization (get-users owner) this client queries.
|
||||
func (c *Client) Org() string { return c.cfg.Organization }
|
||||
|
||||
// User is the trimmed Casdoor user projection the sync consumes.
|
||||
type User struct {
|
||||
Owner string // Casdoor organization
|
||||
Name string // 工号(Casdoor name,登录名口径)
|
||||
DisplayName string // 姓名
|
||||
Email string
|
||||
Phone string
|
||||
IsAdmin bool
|
||||
IsForbidden bool
|
||||
IsDeleted bool
|
||||
DeptName string // 部门名称(按配置/探测字段提取)
|
||||
DeptCode string // 部门编号(按配置/探测字段提取)
|
||||
// DeptSource 记录部门名称取自哪个字段,便于同步结果回显与排障。
|
||||
DeptSource string
|
||||
// Raw preserves the full IdP record for diagnostics and custom mapping.
|
||||
Raw map[string]interface{}
|
||||
}
|
||||
|
||||
// ListUsers pages through every user of the configured organization.
|
||||
// Returns (users, deptFieldUsed, err); deptFieldUsed is empty when no
|
||||
// department value was found on any user.
|
||||
func (c *Client) ListUsers(ctx context.Context) ([]*User, string, error) {
|
||||
if !c.Enabled() {
|
||||
return nil, "", errors.New("casdoor: admin api disabled (set OIDC_AUTH_ADMIN_API_ENABLE and credentials)")
|
||||
}
|
||||
if err := c.ensureToken(ctx); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
users := make([]*User, 0, listPageSize)
|
||||
deptSource := ""
|
||||
for page := 1; page <= listMaxPages; page++ {
|
||||
batch, err := c.listUsersPage(ctx, page)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
users = append(users, batch...)
|
||||
if len(batch) < listPageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, u := range users {
|
||||
c.extractDept(u)
|
||||
if deptSource == "" && u.DeptName != "" {
|
||||
deptSource = u.DeptSource
|
||||
}
|
||||
}
|
||||
return users, deptSource, nil
|
||||
}
|
||||
|
||||
// listUsersPage fetches one page of the directory.
|
||||
func (c *Client) listUsersPage(ctx context.Context, page int) ([]*User, error) {
|
||||
q := url.Values{}
|
||||
q.Set("owner", c.cfg.Organization)
|
||||
q.Set("pageSize", fmt.Sprint(listPageSize))
|
||||
q.Set("p", fmt.Sprint(page))
|
||||
q.Set("accessToken", c.token) // Casdoor's canonical admin-API auth param
|
||||
body, err := c.adminGet(ctx, listUsersPath+"?"+q.Encode())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Casdoor 版本差异:部分构建返回裸数组,部分返回 {"status":..,"data":[..]}
|
||||
// 信封(实测 organization_HX 部署即信封形态)——两种都接受。
|
||||
var wrapped struct {
|
||||
Status string `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
Data []map[string]interface{} `json:"data"`
|
||||
}
|
||||
var rawUsers []map[string]interface{}
|
||||
if err := json.Unmarshal(body, &wrapped); err == nil && wrapped.Data != nil {
|
||||
if wrapped.Status == "error" {
|
||||
return nil, fmt.Errorf("casdoor: get-users failed: %s", wrapped.Msg)
|
||||
}
|
||||
rawUsers = wrapped.Data
|
||||
} else if err := json.Unmarshal(body, &rawUsers); err != nil {
|
||||
// 两种形态都不是 → 尝试按错误对象解读
|
||||
var errObj struct {
|
||||
Status string `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
if json.Unmarshal(body, &errObj) == nil && errObj.Status == "error" {
|
||||
return nil, fmt.Errorf("casdoor: get-users failed: %s", errObj.Msg)
|
||||
}
|
||||
return nil, fmt.Errorf("casdoor: unexpected get-users payload: %w", err)
|
||||
}
|
||||
out := make([]*User, 0, len(rawUsers))
|
||||
for _, raw := range rawUsers {
|
||||
// 缺工号的记录同样保留:由同步服务层记录跳过原因并回显,
|
||||
// 客户端静默丢弃会让操作者无从发现脏数据。
|
||||
out = append(out, userFromRaw(raw))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// adminGet performs an authenticated GET against the admin API, refreshing
|
||||
// the token once on 401 and mapping auth failures to typed errors.
|
||||
func (c *Client) adminGet(ctx context.Context, pathAndQuery string) ([]byte, error) {
|
||||
call := func() (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
|
||||
c.cfg.BaseURL+pathAndQuery, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
return c.http.Do(req)
|
||||
}
|
||||
|
||||
resp, err := call()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("casdoor: request failed: %w", err)
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
||||
_ = resp.Body.Close()
|
||||
// Token might have just expired server-side; refresh once and retry.
|
||||
if refreshErr := c.refreshToken(ctx); refreshErr == nil {
|
||||
if retryResp, retryErr := call(); retryErr == nil {
|
||||
resp = retryResp
|
||||
} else {
|
||||
return nil, ErrAdminDenied
|
||||
}
|
||||
} else {
|
||||
return nil, ErrAdminDenied
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
||||
return nil, ErrAdminDenied
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) // 32MB cap: pages are KB-sized
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("casdoor: read response failed: %w", err)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// ensureToken lazily acquires an access token via client_credentials.
|
||||
func (c *Client) ensureToken(ctx context.Context) error {
|
||||
if c.token != "" && time.Now().Before(c.expiry) {
|
||||
return nil
|
||||
}
|
||||
return c.refreshToken(ctx)
|
||||
}
|
||||
|
||||
// refreshToken exchanges credentials for a fresh access token. Two grant
|
||||
// modes: password grant (service account, preferred when configured — its
|
||||
// user identity passes casdoor's API authz where app tokens get denied) and
|
||||
// client_credentials fallback. Casdoor answers JSON
|
||||
// {"access_token":...,"expires_in":...}; some builds return the bare JWT
|
||||
// with a text content-type — both are accepted.
|
||||
func (c *Client) refreshToken(ctx context.Context) error {
|
||||
form := url.Values{}
|
||||
form.Set("client_id", c.cfg.ClientID)
|
||||
form.Set("client_secret", c.cfg.ClientSecret)
|
||||
if c.cfg.Username != "" && c.cfg.Password != "" {
|
||||
form.Set("grant_type", "password")
|
||||
form.Set("username", c.cfg.Username)
|
||||
form.Set("password", c.cfg.Password)
|
||||
} else {
|
||||
form.Set("grant_type", "client_credentials")
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(c.cfg.BaseURL, "/") + tokenEndpointPath
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint,
|
||||
strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("casdoor: token request failed: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return fmt.Errorf("casdoor: read token response failed: %w", err)
|
||||
}
|
||||
|
||||
token, expiresIn := parseTokenResponse(body)
|
||||
if token == "" {
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized {
|
||||
// Casdoor replies {"error":"unsupported_grant_type",...} when the
|
||||
// application has not enabled the requested grant.
|
||||
if strings.Contains(string(body), "not supported") {
|
||||
return ErrGrantNotSupported
|
||||
}
|
||||
if strings.Contains(string(body), "invalid_grant") && c.cfg.Username != "" {
|
||||
return fmt.Errorf("casdoor: service account login failed: %s",
|
||||
strings.TrimSpace(firstN(string(body), 200)))
|
||||
}
|
||||
return fmt.Errorf("casdoor: token rejected: %s", strings.TrimSpace(firstN(string(body), 200)))
|
||||
}
|
||||
return fmt.Errorf("casdoor: no access_token in response (http %d): %s",
|
||||
resp.StatusCode, firstN(string(body), 200))
|
||||
}
|
||||
ttl := time.Duration(expiresIn) * time.Second
|
||||
if ttl <= 0 {
|
||||
ttl = 10 * time.Minute // Casdoor default when expires_in is absent
|
||||
}
|
||||
// Refresh 60s early to avoid mid-page expiry races.
|
||||
c.token = token
|
||||
c.expiry = time.Now().Add(ttl - minDuration(ttl, time.Minute))
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseTokenResponse extracts (access_token, expires_in) tolerating JSON or
|
||||
// bare-JWT bodies.
|
||||
func parseTokenResponse(body []byte) (string, int64) {
|
||||
trimmed := strings.TrimSpace(string(body))
|
||||
if strings.HasPrefix(trimmed, "{") {
|
||||
var parsed struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(trimmed), &parsed); err == nil {
|
||||
return parsed.AccessToken, parsed.ExpiresIn
|
||||
}
|
||||
}
|
||||
// Bare JWT (eyJ...) — usable directly as a bearer token.
|
||||
if strings.Contains(trimmed, ".") && !strings.ContainsAny(trimmed, " \n{}") {
|
||||
return trimmed, 0
|
||||
}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 字段提取
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// deptNameCandidates 部门名称的内置探测顺序:Casdoor 部署差异较大(分组树 /
|
||||
// affiliation / title / properties),探测到第一个非空值即用并在结果里回显
|
||||
// 字段名;部署方可通过 OIDC_AUTH_ADMIN_DEPT_FIELD 固定。
|
||||
var deptNameCandidates = []string{
|
||||
"department",
|
||||
"dept",
|
||||
"deptName",
|
||||
"affiliation",
|
||||
"title",
|
||||
"organization",
|
||||
}
|
||||
|
||||
// deptCodeCandidates 部门编号的内置探测顺序。
|
||||
var deptCodeCandidates = []string{
|
||||
"departmentCode",
|
||||
"deptCode",
|
||||
"dept_code",
|
||||
"department_code",
|
||||
"deptNo",
|
||||
}
|
||||
|
||||
// groupCandidates 分组树字段(值可为 []string 或以 / 分隔的字符串);
|
||||
// 分组路径取末段作为部门名(如 "公司/财务部" → "财务部")。
|
||||
var groupCandidates = []string{"groups", "groupPath", "group_paths"}
|
||||
|
||||
// extractDept fills DeptName/DeptCode/DeptSource for one user.
|
||||
func (c *Client) extractDept(u *User) {
|
||||
if u == nil || u.Raw == nil {
|
||||
return
|
||||
}
|
||||
if c.cfg.DeptField != "" {
|
||||
if v := stringField(u.Raw, c.cfg.DeptField); v != "" {
|
||||
u.DeptName = v
|
||||
u.DeptSource = c.cfg.DeptField
|
||||
}
|
||||
} else {
|
||||
for _, key := range deptNameCandidates {
|
||||
if v := stringField(u.Raw, key); v != "" {
|
||||
u.DeptName = v
|
||||
u.DeptSource = key
|
||||
break
|
||||
}
|
||||
}
|
||||
if u.DeptName == "" {
|
||||
for _, key := range groupCandidates {
|
||||
if v := firstGroupLeaf(u.Raw, key); v != "" {
|
||||
u.DeptName = v
|
||||
u.DeptSource = key
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.cfg.DeptCodeField != "" {
|
||||
u.DeptCode = stringField(u.Raw, c.cfg.DeptCodeField)
|
||||
} else {
|
||||
for _, key := range deptCodeCandidates {
|
||||
if v := stringField(u.Raw, key); v != "" {
|
||||
u.DeptCode = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stringField reads a string field from the raw user record. Dotted keys
|
||||
// (e.g. "properties.department") drill into nested maps.
|
||||
func stringField(raw map[string]interface{}, key string) string {
|
||||
parts := strings.Split(key, ".")
|
||||
var cur interface{} = raw
|
||||
for _, p := range parts {
|
||||
m, ok := cur.(map[string]interface{})
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
cur, ok = m[p]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
switch v := cur.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(v)
|
||||
case float64: // JSON numbers decode as float64
|
||||
return strings.TrimSpace(fmt.Sprint(v))
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// firstGroupLeaf extracts the leaf segment of the first non-empty group path.
|
||||
// Accepts []string / []interface{} / "a/b/c" string forms.
|
||||
func firstGroupLeaf(raw map[string]interface{}, key string) string {
|
||||
v, ok := raw[key]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch val := v.(type) {
|
||||
case []interface{}:
|
||||
for _, item := range val {
|
||||
if s, ok := item.(string); ok && strings.TrimSpace(s) != "" {
|
||||
return groupLeaf(s)
|
||||
}
|
||||
}
|
||||
case []string:
|
||||
for _, s := range val {
|
||||
if strings.TrimSpace(s) != "" {
|
||||
return groupLeaf(s)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
if strings.TrimSpace(val) != "" {
|
||||
return groupLeaf(val)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// groupLeaf takes the last path segment of a group reference
|
||||
// ("公司/财务部" → "财务部"; "财务部" → "财务部").
|
||||
func groupLeaf(path string) string {
|
||||
path = strings.TrimSpace(path)
|
||||
if idx := strings.LastIndex(path, "/"); idx >= 0 && idx < len(path)-1 {
|
||||
path = path[idx+1:]
|
||||
}
|
||||
return strings.TrimSpace(path)
|
||||
}
|
||||
|
||||
// userFromRaw projects a raw Casdoor user record.
|
||||
func userFromRaw(raw map[string]interface{}) *User {
|
||||
u := &User{Raw: raw}
|
||||
u.Owner = stringField(raw, "owner")
|
||||
u.Name = stringField(raw, "name")
|
||||
u.DisplayName = stringField(raw, "displayName")
|
||||
if u.DisplayName == "" {
|
||||
u.DisplayName = stringField(raw, "nickname")
|
||||
}
|
||||
u.Email = strings.ToLower(stringField(raw, "email"))
|
||||
u.Phone = stringField(raw, "phone")
|
||||
u.IsAdmin = boolField(raw, "isAdmin") || boolField(raw, "isGlobalAdmin")
|
||||
u.IsForbidden = boolField(raw, "isForbidden")
|
||||
u.IsDeleted = boolField(raw, "isDeleted")
|
||||
return u
|
||||
}
|
||||
|
||||
func boolField(raw map[string]interface{}, key string) bool {
|
||||
if v, ok := raw[key].(bool); ok {
|
||||
return v
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LogSyncDisabled 帮助 handler 在未配置时输出明确日志(客户端为 nil 安全)。
|
||||
func LogSyncDisabled(ctx context.Context) {
|
||||
logger.Warnf(ctx, "casdoor member sync is disabled: set OIDC_AUTH_ADMIN_API_ENABLE=true plus admin API env overrides")
|
||||
}
|
||||
|
||||
// firstN returns the first n bytes of s (rune-safe truncation is unnecessary
|
||||
// here: the content is a JSON error line).
|
||||
func firstN(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func minDuration(a, b time.Duration) time.Duration {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -64,6 +64,11 @@ var noAuthAPI = map[string][]string{
|
||||
// template key + 20-day expiry), never by caller-supplied ids. HEAD is
|
||||
// allowed for the same preview-validation reason as /files/presigned.
|
||||
"/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
|
||||
// before GET to validate Content-Type / Content-Length when rendering
|
||||
// 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
|
||||
// error middleware as the rest of the auth surface.
|
||||
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) {
|
||||
ip := c.ClientIP()
|
||||
if !publicAuthLimiter.allow(ip) {
|
||||
if !l.allow(ip) {
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrTooManyRequests,
|
||||
Message: "too many requests; please retry shortly",
|
||||
|
||||
@@ -337,7 +337,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
|
||||
RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
|
||||
RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards)
|
||||
RegisterOrgRoutes(v1, params.OrgCenterHandler, rbacGuards)
|
||||
RegisterOrgRoutes(v1, params.OrgCenterHandler, params.TrainingHandler, rbacGuards)
|
||||
RegisterChunkerDebugRoutes(v1, rbacGuards)
|
||||
|
||||
// Fail fast if any declared API-key policy points at a route
|
||||
|
||||
@@ -118,6 +118,10 @@ func RegisterTenantRoutes(
|
||||
if memberHandler != nil {
|
||||
g.apiKeyRoute(tenantByID, http.MethodGet, "/members", apiKeyManageMembers(apiKeyFullAccess()), g.Viewer(), memberHandler.ListMembers)
|
||||
g.apiKeyRoute(tenantByID, http.MethodPost, "/members", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.AddMember)
|
||||
// Excel 花名册批量导入:与其他成员变更一样仅 Owner 可用。
|
||||
g.apiKeyRoute(tenantByID, http.MethodPost, "/members/import", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.ImportMembers)
|
||||
// Casdoor 用户目录同步(000156):管理 API 拉用户自动开户/入空间。
|
||||
g.apiKeyRoute(tenantByID, http.MethodPost, "/members/sync-casdoor", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.SyncCasdoorMembers)
|
||||
g.apiKeyRoute(tenantByID, http.MethodPut, "/members/:user_id", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.UpdateMemberRole)
|
||||
g.apiKeyRoute(tenantByID, http.MethodDelete, "/members/:user_id", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.RemoveMember)
|
||||
tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant)
|
||||
|
||||
@@ -2,6 +2,7 @@ package router
|
||||
|
||||
import (
|
||||
"academy/internal/handler/orgcenter"
|
||||
"academy/internal/handler/training"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -11,7 +12,12 @@ import (
|
||||
// - 空间 RBAC 把关:读 Viewer+,写 Contributor+;
|
||||
// - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知;
|
||||
// - 不对 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 {
|
||||
return
|
||||
}
|
||||
@@ -28,6 +34,23 @@ func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards)
|
||||
orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers)
|
||||
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.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"academy/internal/handler/training"
|
||||
"academy/internal/middleware"
|
||||
"academy/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -24,7 +25,16 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
|
||||
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
|
||||
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)
|
||||
@@ -93,6 +103,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
// 发布/下线(000154):静态段 :action 须先于 :id 参数段注册区分
|
||||
trainingGroup.POST("/course-library/:id/publish", g.Contributor(), h.SetCourseLibraryPublishStatus)
|
||||
trainingGroup.POST("/course-library/:id/offline", g.Contributor(), h.SetCourseLibraryPublishStatus)
|
||||
// 核验(000157):单个/批量共用(ids 数组),仅课长/经理限本部门。
|
||||
trainingGroup.POST("/course-library/verify", g.Contributor(), h.VerifyCourseLibraryItems)
|
||||
// 导入/导出:与需求域同口径(前端解析 Excel 后按行提交;导出 xlsx 下载)。
|
||||
trainingGroup.POST("/course-library/import", g.Contributor(), h.ImportCourseLibrary)
|
||||
trainingGroup.POST("/course-library/export", g.Contributor(), h.ExportCourseLibrary)
|
||||
@@ -100,6 +112,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial)
|
||||
// material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。
|
||||
trainingGroup.POST("/course-library/:id/material/from-kb", g.Contributor(), h.AttachCourseLibraryMaterialFromKb)
|
||||
// material/remove 移除课件(名称登记保留,课件变更即回待核验)。
|
||||
trainingGroup.POST("/course-library/:id/material/remove", g.Contributor(), h.RemoveCourseLibraryMaterial)
|
||||
trainingGroup.GET("/course-library/:id/material/file", h.CourseLibraryMaterialFile)
|
||||
// ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ----
|
||||
trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks)
|
||||
@@ -127,8 +141,12 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
|
||||
// ---- 签到域 ----
|
||||
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.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.POST("/sign-records/:id/review", g.Contributor(), h.ReviewSignRecord)
|
||||
trainingGroup.GET("/sessions/:id/sign-summary", h.SignSummary)
|
||||
@@ -163,6 +181,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
trainingGroup.GET("/learning-progress", h.ListMyCourseProgress)
|
||||
trainingGroup.GET("/learning-tasks", h.ListMyLearningTasks)
|
||||
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/:id/reply", g.Contributor(), h.ReplyFeedback)
|
||||
trainingGroup.GET("/course-feedbacks/pending", h.ListPendingFeedbacks)
|
||||
|
||||
@@ -50,6 +50,13 @@ const (
|
||||
// AuditActionInvitationExpired fires when the lazy sweep transitions
|
||||
// an overdue pending row to expired. Actor is empty (system).
|
||||
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.
|
||||
// Cover both env-store-derived (__env_*) and DB store create /
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package types
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Casdoor 成员同步(设置 → 成员管理 → 同步CASDOOR成员,000156):
|
||||
// 后端经 Casdoor 管理 API(client_credentials)拉全量用户 → 自动开户/入空间,
|
||||
// 同时把部门编号/名称落 org_depts(组织架构)与 users.dept_code/dept_name。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// CasdoorSyncResult 是一次同步的汇总结果,前端结果弹窗直接消费。
|
||||
type CasdoorSyncResult struct {
|
||||
// Total 是 Casdoor 侧拉到的用户数(含被跳过的)。
|
||||
Total int `json:"casdoor_total"`
|
||||
// UsersCreated 本次新建的平台账号数(已存在的不计)。
|
||||
UsersCreated int `json:"users_created"`
|
||||
// MembersAdded 本次新加入空间的成员数。
|
||||
MembersAdded int `json:"members_added"`
|
||||
// MembersExist 已经是空间成员的数量(角色保持不变)。
|
||||
MembersExist int `json:"members_existing"`
|
||||
// DeptsCreated 本次在组织架构新建的部门数(按编号/名称匹配已有的不重复建)。
|
||||
DeptsCreated int `json:"depts_created"`
|
||||
// DeptSource 部门名称取自 Casdoor 的哪个字段(空=用户无部门数据,未同步部门)。
|
||||
DeptSource string `json:"dept_source,omitempty"`
|
||||
// Skipped 逐条列出被跳过的用户与原因(单条失败不阻断整批)。
|
||||
Skipped []CasdoorSyncSkip `json:"skipped,omitempty"`
|
||||
}
|
||||
|
||||
// CasdoorSyncSkip 一条被跳过的记录。
|
||||
type CasdoorSyncSkip struct {
|
||||
// Name 工号(Casdoor name);缺失时留空。
|
||||
Name string `json:"name"`
|
||||
// Email Casdoor 侧邮箱(可能为空)。
|
||||
Email string `json:"email,omitempty"`
|
||||
// Reason 跳过原因(停用/无工号/开户失败等),直接展示给操作者。
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// CasdoorMemberSyncService 同步 Casdoor 用户目录到空间成员(000156):
|
||||
// 成员管理「同步CASDOOR成员」按钮背后的业务层。单向增量、幂等——只新增,
|
||||
// 不删除、不停用、不改已有成员角色;部门编号/名称回写 users.dept_* 并
|
||||
// 落到组织架构 org_depts(供「从平台用户添加」自动带部门)。
|
||||
type CasdoorMemberSyncService interface {
|
||||
// SyncMembers 拉取 Casdoor 全量用户并与当前空间对齐:
|
||||
// 1. 无账号者自动开户(随机密码、tenantless、OIDC-only,首次登录收编);
|
||||
// 2. 非成员者以 viewer 加入空间;
|
||||
// 3. Casdoor 有部门数据时同步 org_depts 并回写 users.dept_*。
|
||||
// operatorID 用于审计与 invited_by 归因(可为空)。
|
||||
SyncMembers(ctx context.Context, tenantID uint64, operatorID string) (*types.CasdoorSyncResult, error)
|
||||
}
|
||||
@@ -22,14 +22,21 @@ type OrgCenterRepository interface {
|
||||
GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error)
|
||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*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
|
||||
DeleteEmployee(ctx context.Context, tenantID uint64, id string) error
|
||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||
|
||||
// ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。
|
||||
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
||||
// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。
|
||||
ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error)
|
||||
// GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。
|
||||
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)
|
||||
@@ -52,12 +59,21 @@ type OrgCenterService interface {
|
||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
||||
// ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。
|
||||
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)
|
||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||
|
||||
// ListTenantUsers 平台用户列表(员工导入选择器数据源)。
|
||||
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)
|
||||
PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// TenantBootstrapService seeds "out-of-the-box" defaults into a freshly
|
||||
// created workspace so a new user can use the platform without manually
|
||||
// configuring models first: a starter knowledge base bound to the built-in
|
||||
// default chat/embedding models, a welcome document inside it, and the
|
||||
// tenant-level rerank model. All steps are best-effort (fail-open) — a
|
||||
// bootstrap failure must never fail tenant creation or registration.
|
||||
type TenantBootstrapService interface {
|
||||
// SeedTenantDefaults is idempotent: workspaces that already contain the
|
||||
// bootstrap knowledge base are skipped. ownerUserID (may be empty for
|
||||
// platform-managed tenants) is recorded as the KB creator.
|
||||
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)
|
||||
}
|
||||
@@ -18,6 +18,9 @@ type TrainingListQuery struct {
|
||||
// LecturerID 讲师数据范围过滤(handler 按调用方角色强制注入:
|
||||
// 纯讲师只能看到自己讲师相关的课程/场次)。
|
||||
LecturerID string
|
||||
// RelatedUserID 课程管理「与我相关」范围过滤(handler 对无维护角色的用户
|
||||
// 强制注入:仅可见自己创建或自己授课的课程)。
|
||||
RelatedUserID string
|
||||
// Scope 视图口径:"student"=学员目录视图(已发布课程/全场次),用于区分
|
||||
// 讲师的学习视角与其课程维护视角(handler 按此决定是否注入讲师过滤)。
|
||||
Scope string
|
||||
@@ -26,6 +29,13 @@ type TrainingListQuery struct {
|
||||
Keyword string
|
||||
Page int
|
||||
PageSize int
|
||||
// 课程管理学员目录口径(000160,scope=catalog 时 handler 注入):
|
||||
// CatalogOnly 仅返回已发布课程,且适合人员须覆盖调用方 ——
|
||||
// suitable='全部' 或 =调用方部门名;未设置适合人员的存量课程沿用
|
||||
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。
|
||||
CatalogOnly bool
|
||||
CatalogDeptID string
|
||||
CatalogDeptName string
|
||||
}
|
||||
|
||||
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
|
||||
@@ -39,6 +49,12 @@ type TrainingRepository interface {
|
||||
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。
|
||||
GetMember(ctx context.Context, tenantID uint64, id 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(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error)
|
||||
ListPosts(ctx context.Context, tenantID uint64) ([]string, error)
|
||||
@@ -80,10 +96,15 @@ type TrainingRepository interface {
|
||||
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
|
||||
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, 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
|
||||
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
||||
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
|
||||
UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
|
||||
// ConfirmCourseLibraryItems 批量核验课程条目(000157):仅 pending 行置为
|
||||
// confirmed 并回填核验人/时间,返回实际核验行数。
|
||||
ConfirmCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID string) (int64, error)
|
||||
BatchCreateCourseLibrary(ctx context.Context, items []*types.TrainingCourseLibrary) error
|
||||
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
|
||||
|
||||
@@ -96,6 +117,11 @@ type TrainingRepository interface {
|
||||
ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
|
||||
// CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。
|
||||
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(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error)
|
||||
// CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。
|
||||
@@ -118,9 +144,14 @@ type TrainingRepository interface {
|
||||
UpsertSignCode(ctx context.Context, code *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)
|
||||
// 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
|
||||
GetSignRecord(ctx context.Context, tenantID uint64, sessionID, memberID 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)
|
||||
ReviewSignRecord(ctx context.Context, record *types.TrainingSignRecord) error
|
||||
SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error)
|
||||
@@ -259,6 +290,9 @@ type TrainingService interface {
|
||||
SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error)
|
||||
// CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。
|
||||
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)
|
||||
@@ -266,7 +300,8 @@ type TrainingService interface {
|
||||
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
|
||||
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
|
||||
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
|
||||
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error)
|
||||
// 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)
|
||||
DeleteDemand(ctx context.Context, tenantID uint64, id string) error
|
||||
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
|
||||
@@ -300,9 +335,14 @@ type TrainingService interface {
|
||||
SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154)。
|
||||
SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
|
||||
// VerifyCourseLibraryItems 批量核验课程条目(000157,仅本部门课长/经理):
|
||||
// deptScope 为调用方所在部门(恒非空),仅核验所属部门匹配的条目。
|
||||
VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (verified int64, skipped int64, err error)
|
||||
// GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。
|
||||
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
|
||||
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
|
||||
// DeleteCourseLibraryItem 软删课程条目(仅待核验状态可删;deptScope 非空时
|
||||
// 校验所属部门匹配,000157 仅课长/经理限本部门)。
|
||||
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id, deptScope string) error
|
||||
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后按行提交)。
|
||||
ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error)
|
||||
// ExportCourseLibrary 导出 Excel(excelize;ids 空 = 全量)。
|
||||
@@ -314,6 +354,8 @@ type TrainingService interface {
|
||||
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
|
||||
// 已有文档作为课程课件(与上传同步同口径)。
|
||||
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
// RemoveCourseLibraryMaterial 移除课程课件(文件/知识库挂接清空,名称登记保留)。
|
||||
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error)
|
||||
|
||||
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
|
||||
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
|
||||
@@ -335,14 +377,26 @@ type TrainingService interface {
|
||||
|
||||
// 签到域
|
||||
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)
|
||||
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(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)
|
||||
ReviewSignRecord(ctx context.Context, tenantID uint64, recordID, decision, operatorID string) (*types.TrainingSignRecord, 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)
|
||||
// ---- 企微扫码签到免登(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 落对象存储。
|
||||
@@ -415,6 +469,9 @@ type TrainingService interface {
|
||||
// ListMyCourseProgress 当前用户在某课程下各课件的学习进度(学习详情页回读)。
|
||||
ListMyCourseProgress(ctx context.Context, tenantID uint64, userID, courseID string) ([]*types.TrainingLearningProgress, 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(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)
|
||||
|
||||
@@ -51,6 +51,12 @@ type UserService interface {
|
||||
ValidatePassword(ctx context.Context, userID string, password string) error
|
||||
// GenerateTokens generates access and refresh tokens for user
|
||||
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
|
||||
// the login-response shape. activeTenant is reused (without an extra
|
||||
// lookup) for the matching row's TenantName. The slice is guaranteed
|
||||
|
||||
+55
-27
@@ -23,14 +23,14 @@ const (
|
||||
|
||||
// OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。
|
||||
type OrgDept struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"`
|
||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||
Code string `json:"code" gorm:"type:varchar(64);default:''"`
|
||||
Sort int `json:"sort" gorm:"default:0"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"`
|
||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||
Code string `json:"code" gorm:"type:varchar(64);default:''"`
|
||||
Sort int `json:"sort" gorm:"default:0"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
@@ -39,17 +39,17 @@ func (OrgDept) TableName() string { return "org_depts" }
|
||||
|
||||
// OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。
|
||||
type OrgEmployee struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
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"`
|
||||
EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"`
|
||||
Post string `json:"post" gorm:"type:varchar(128);default:''"`
|
||||
LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"`
|
||||
WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"`
|
||||
Status string `json:"status" gorm:"type:varchar(16);default:'active'"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
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"`
|
||||
EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"`
|
||||
Post string `json:"post" gorm:"type:varchar(128);default:''"`
|
||||
LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"`
|
||||
WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"`
|
||||
Status string `json:"status" gorm:"type:varchar(16);default:'active'"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
|
||||
// 联查只读展示字段(不落库):
|
||||
@@ -76,14 +76,14 @@ func (m *OrgEmployee) OrgRoleList() []string {
|
||||
|
||||
// OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。
|
||||
type OrgModuleMember struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
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"`
|
||||
EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"`
|
||||
Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"`
|
||||
Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
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"`
|
||||
EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"`
|
||||
Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"`
|
||||
Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||
}
|
||||
|
||||
@@ -97,3 +97,31 @@ type OrgListQuery struct {
|
||||
Page 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"`
|
||||
}
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user