Compare commits
11
Commits
master
..
448fbcdaff
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
448fbcdaff | ||
|
|
8f225ecea9 | ||
|
|
196478114c | ||
|
|
42042ca8bd | ||
|
|
7e1e670f0a | ||
|
|
8bd02e7c7e | ||
|
|
4112de0703 | ||
|
|
6594f97e3c | ||
|
|
0819f8c4d1 | ||
|
|
3c8b595064 | ||
|
|
11ce1c3c0c |
No files matched your search
@@ -22,9 +22,13 @@ jobs:
|
|||||||
set -e
|
set -e
|
||||||
cd "$DEPLOY_DIR"
|
cd "$DEPLOY_DIR"
|
||||||
git fetch origin
|
git fetch origin
|
||||||
git checkout -q -B test origin/test
|
# 幂等发布:部署目录若残留未提交改动/未跟踪文件(如服务器上临时调试遗留),
|
||||||
|
# 先整体 stash 留底(-u 含未跟踪文件;不碰 .gitignore 的本地配置),再强制对齐远端
|
||||||
|
git stash push -u -m "deploy-autostash $(date +%F_%T)" || true
|
||||||
|
git checkout -f -q -B test origin/test
|
||||||
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
|
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
|
||||||
echo "当前部署提交: $(git log --oneline -1)"
|
echo "当前部署提交: $(git log --oneline -1)"
|
||||||
|
echo "同步后残留脏文件: $(git status --porcelain | wc -l) 项"
|
||||||
|
|
||||||
- name: 构建镜像(app + frontend,ARM64 原生)
|
- name: 构建镜像(app + frontend,ARM64 原生)
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -73,5 +73,10 @@ miniprogram/project.private.config.json
|
|||||||
# Locally built BrowserSkill runtime and extension bundles
|
# Locally built BrowserSkill runtime and extension bundles
|
||||||
/artifacts/browserskill/
|
/artifacts/browserskill/
|
||||||
|
|
||||||
|
# Offline Docker build fast-path artifacts (prebuilt binary + runtime deps,
|
||||||
|
# carried on the build host only — never committed, see docker/Dockerfile.app)
|
||||||
|
/docker/prebuilt/
|
||||||
|
|
||||||
# Local DuckDB extension extraction scratch dir (training template debugging)
|
# Local DuckDB extension extraction scratch dir (training template debugging)
|
||||||
tmp-extract-duckdb/
|
tmp-extract-duckdb/
|
||||||
|
.cgo-sqlite/
|
||||||
+22
-3
@@ -83,10 +83,20 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
|||||||
# so that module's go.mod must exist before `go mod download`.
|
# so that module's go.mod must exist before `go mod download`.
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod
|
COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod
|
||||||
|
# 离线快速通道(网络受限环境):docker/prebuilt/ 携带宿主机交叉编译的产物时,
|
||||||
|
# 跳过 go mod download 等联网步骤,直接装填预构建二进制与 gojieba 运行时依赖。
|
||||||
|
# 目录不入库(与 artifacts/browserskill 同口径),上游构建走下方原有路径不受影响。
|
||||||
|
COPY docker/prebuilt/ /app/prebuilt/
|
||||||
# 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖,
|
# 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖,
|
||||||
# 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载)
|
# 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载)
|
||||||
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
||||||
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/
|
if [ -f /app/prebuilt/Academy ]; then \
|
||||||
|
mkdir -p /go/pkg/mod/github.com/yanyiwu && \
|
||||||
|
tar -xzf /app/prebuilt/yanyiwu.tar.gz -C /go/pkg/mod/github.com/yanyiwu && \
|
||||||
|
cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
|
||||||
|
else \
|
||||||
|
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
|
||||||
|
fi
|
||||||
COPY cmd/download cmd/download
|
COPY cmd/download cmd/download
|
||||||
# DuckDB extensions (spatial/excel): prefer a local seed tarball exported from
|
# DuckDB extensions (spatial/excel): prefer a local seed tarball exported from
|
||||||
# a previously built image (artifacts/duckdb_extensions/seed.tar) —
|
# a previously built image (artifacts/duckdb_extensions/seed.tar) —
|
||||||
@@ -100,7 +110,13 @@ RUN if [ -s /tmp/duckdb-seed.tar ]; then \
|
|||||||
go run cmd/download/duckdb/duckdb.go; \
|
go run cmd/download/duckdb/duckdb.go; \
|
||||||
fi
|
fi
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN bash ./scripts/copy-licenses.sh /license-bundle
|
# license 归档属发布输入(联网逐模块校验),离线快速通道下跳过,不影响运行时功能
|
||||||
|
RUN if [ -f /app/prebuilt/Academy ]; then \
|
||||||
|
echo "==> Offline fast-path: skip license bundle"; \
|
||||||
|
mkdir -p /license-bundle/licenses/sources; \
|
||||||
|
else \
|
||||||
|
bash ./scripts/copy-licenses.sh /license-bundle; \
|
||||||
|
fi
|
||||||
|
|
||||||
# Get version and commit info for build injection
|
# Get version and commit info for build injection
|
||||||
ARG VERSION_ARG
|
ARG VERSION_ARG
|
||||||
@@ -163,7 +179,10 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
|
|||||||
objcopy --remove-section "$s" "$a" || true; \
|
objcopy --remove-section "$s" "$a" || true; \
|
||||||
done; \
|
done; \
|
||||||
done; \
|
done; \
|
||||||
if [ "$WITH_ANYDOC" = "1" ]; then \
|
if [ -f /app/prebuilt/Academy ]; then \
|
||||||
|
echo "==> Using prebuilt binary from docker/prebuilt/"; \
|
||||||
|
cp /app/prebuilt/Academy /app/Academy; \
|
||||||
|
elif [ "$WITH_ANYDOC" = "1" ]; then \
|
||||||
make build-prod GO_BUILD_TAGS=anydoc; \
|
make build-prod GO_BUILD_TAGS=anydoc; \
|
||||||
else \
|
else \
|
||||||
make build-prod; \
|
make build-prod; \
|
||||||
|
|||||||
+5
-3
@@ -43,9 +43,11 @@
|
|||||||
|
|
||||||
| 项 | 值 |
|
| 项 | 值 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 生产服入口 | http://192.168.100.230:8802(域名绑定待 DNS 管理员登记后更新) |
|
| 生产服入口 | **https://kb.well-trust.com**(ai30 nginx 443 反代 8802;备选直连 http://192.168.100.230:8802) |
|
||||||
|
| 测试服入口 | **https://kbt.well-trust.com**(同一证书/vhost 反代 hxtesting 8801;备选 http://192.168.100.192:8801) |
|
||||||
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
|
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
|
||||||
| 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) |
|
| 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) |
|
||||||
| 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 `http://192.168.100.230:8802/api/v1/auth/oidc/callback`(域名定稿后同步追加域名回调);client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) |
|
| 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 IP 与 https://kb.well-trust.com 两路 + localhost:5173;client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) |
|
||||||
| Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行前快照) |
|
| Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行)、`application_bak_20261120`(域名回调更新前) |
|
||||||
| 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) |
|
| 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) |
|
||||||
|
| 域名/证书 | kb+kbt SAN 一张(`/data/ai-platform/.certbot/config/live/kb.well-trust.com/`),DNS A 记录与 TXT 验证均走阿里 API(凭据 `aliyun-welltrust.ini`)自动完成,续期 dns-aliyun 全自动;vhost=`/etc/nginx/conf.d/kb-academy.conf`(预写件 `/data/ai-platform/kb-academy-nginx.conf`,装载需一次 sudo) |
|
||||||
@@ -47,8 +47,8 @@
|
|||||||
|
|
||||||
| 项 | 值 |
|
| 项 | 值 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 测试服入口 | http://192.168.100.192:8801(FRONTEND_PORT=8801,登记册 88xx 平台段) |
|
| 测试服入口 | **https://kbt.well-trust.com**(ai30 nginx 反代;备选 http://192.168.100.192:8801,FRONTEND_PORT=8801,登记册 88xx 平台段) |
|
||||||
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
|
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
|
||||||
| 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) |
|
| 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) |
|
||||||
| 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 与本地 5173) |
|
| 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 / https://kbt.well-trust.com 与本地 5173) |
|
||||||
| 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) |
|
| 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) |
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<title>AIDO</title>
|
<title>和信智汇学院</title>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||||
|
|||||||
@@ -119,12 +119,12 @@ const persistOIDCLoginResponse = async (response: any) => {
|
|||||||
if (result.ok) MessagePlugin.success(t('inviteRegister.joined'))
|
if (result.ok) MessagePlugin.success(t('inviteRegister.joined'))
|
||||||
else MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
else MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||||
// 会话已有效,无论 token 是否兑换成功都进入应用。
|
// 会话已有效,无论 token 是否兑换成功都进入应用。
|
||||||
router.replace('/platform/knowledge-bases')
|
router.replace('/platform/creatChat')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await nextTick()
|
await nextTick()
|
||||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleGlobalOIDCCallback = async () => {
|
const handleGlobalOIDCCallback = async () => {
|
||||||
|
|||||||
@@ -118,6 +118,8 @@ export interface UserInfo {
|
|||||||
username: string
|
username: string
|
||||||
email: string
|
email: string
|
||||||
avatar?: string
|
avatar?: string
|
||||||
|
// 姓名/显示名(工号式账号的 username 是工号,界面展示姓名用;未设置为空串)
|
||||||
|
display_name?: string
|
||||||
tenant_id: string
|
tenant_id: string
|
||||||
can_access_all_tenants?: boolean
|
can_access_all_tenants?: boolean
|
||||||
preferences?: UserPreferences
|
preferences?: UserPreferences
|
||||||
@@ -158,6 +160,7 @@ export function userInfoFromApi(
|
|||||||
username: u?.username || '',
|
username: u?.username || '',
|
||||||
email: u?.email || '',
|
email: u?.email || '',
|
||||||
avatar: u?.avatar,
|
avatar: u?.avatar,
|
||||||
|
display_name: u?.display_name || '',
|
||||||
tenant_id: String(tid) || '',
|
tenant_id: String(tid) || '',
|
||||||
can_access_all_tenants: u?.can_access_all_tenants === true,
|
can_access_all_tenants: u?.can_access_all_tenants === true,
|
||||||
is_system_admin: u?.is_system_admin === true,
|
is_system_admin: u?.is_system_admin === true,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { get, post, put, del } from '@/utils/request'
|
import { get, post, put, del } from '@/utils/request'
|
||||||
|
import type { WecomSyncSummary } from '@/api/training'
|
||||||
|
|
||||||
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
|
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
|
||||||
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
|
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
|
||||||
@@ -42,6 +43,8 @@ export interface OrgEmployee {
|
|||||||
post: string
|
post: string
|
||||||
lecturer_rate: number
|
lecturer_rate: number
|
||||||
status: string
|
status: string
|
||||||
|
/** 企微账号(OA 同步/绑定维护;列表 Select org_employees.* 随行返回)。 */
|
||||||
|
wecom_userid?: string
|
||||||
/** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */
|
/** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */
|
||||||
user_name?: string
|
user_name?: string
|
||||||
dept_name?: string
|
dept_name?: string
|
||||||
@@ -115,6 +118,64 @@ export interface OrgUpdateEmployee {
|
|||||||
export const updateEmployee = (id: string, payload: OrgUpdateEmployee) =>
|
export const updateEmployee = (id: string, payload: OrgUpdateEmployee) =>
|
||||||
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}`, payload)
|
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}`, payload)
|
||||||
|
|
||||||
|
// ---- 职称角色 / 企微账号(自培训域迁入组织架构页;/org 域别名路由复用培训
|
||||||
|
// handler,角色绑定仍写 module_key='training';权限细控 HR/经理在 handler 内) ----
|
||||||
|
|
||||||
|
/** 设置员工职称角色(学员为全员隐式角色,由后端保留,前端保存时一并带上)。 */
|
||||||
|
export const updateOrgEmployeeRoles = (id: string, roles: string[]) =>
|
||||||
|
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/roles`, { roles })
|
||||||
|
|
||||||
|
/** 维护员工企微账号(培训提醒推送目标;留空即解绑)。 */
|
||||||
|
export const updateOrgEmployeeWecomUserid = (id: string, wecomUserid: string) =>
|
||||||
|
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/wecom-userid`, {
|
||||||
|
wecom_userid: wecomUserid,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式,预览只读)。 */
|
||||||
|
export const previewOrgWecomSync = () =>
|
||||||
|
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/preview`)
|
||||||
|
|
||||||
|
/** OA 同步写入(无冲突时才落库,返回写入统计)。 */
|
||||||
|
export const applyOrgWecomSync = () =>
|
||||||
|
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/apply`)
|
||||||
|
|
||||||
|
// ---- 归属空间收编(登录默认落点;后端 Owner 限定) ----
|
||||||
|
// 员工首登自动开通个人空间后,归属指针(users.tenant_id)停在个人空间,登录后
|
||||||
|
// 看到的组织架构/培训是个人空间那份空数据;收编把默认落点改回本空间,
|
||||||
|
// 成员关系与个人空间数据不变(可经空间切换器改回,非破坏性)。
|
||||||
|
|
||||||
|
/** 可收编成员:归属空间不在本空间的活跃成员。 */
|
||||||
|
export interface OrgAdoptableUser {
|
||||||
|
id: string
|
||||||
|
username: string
|
||||||
|
display_name: string
|
||||||
|
email: string
|
||||||
|
home_tenant_id: number
|
||||||
|
home_tenant_name: string
|
||||||
|
in_roster: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单条收编跳过记录(非本空间成员/停用/跨空间账号等,原因逐条回传)。 */
|
||||||
|
export interface OrgAdoptSkip {
|
||||||
|
user_id: string
|
||||||
|
username: string
|
||||||
|
display_name: string
|
||||||
|
reason: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrgAdoptResult {
|
||||||
|
adopted: number
|
||||||
|
skipped: OrgAdoptSkip[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收编预览:归属空间不在本空间的活跃成员列表。 */
|
||||||
|
export const listAdoptableUsers = () =>
|
||||||
|
get<{ success: boolean; data: OrgAdoptableUser[] }>(`${base}/employees/adoptable`)
|
||||||
|
|
||||||
|
/** 批量收编:把成员的归属空间(登录默认落点)改为本空间。 */
|
||||||
|
export const adoptHomeTenant = (userIds: string[]) =>
|
||||||
|
post<{ success: boolean; data: OrgAdoptResult }>(`${base}/employees/adopt-home`, { user_ids: userIds })
|
||||||
|
|
||||||
// ---- 模块角色绑定 ----
|
// ---- 模块角色绑定 ----
|
||||||
|
|
||||||
export const listModuleMembers = (moduleKey: OrgModuleKey) =>
|
export const listModuleMembers = (moduleKey: OrgModuleKey) =>
|
||||||
|
|||||||
@@ -162,6 +162,8 @@ export interface TrainingDemand {
|
|||||||
dept_id: string
|
dept_id: string
|
||||||
submitter_id: string
|
submitter_id: string
|
||||||
course_name: string
|
course_name: string
|
||||||
|
/** 需求所填课程自动匹配的课程管理条目 id(000158:填报/导入时按名称精准匹配,未命中自动新增待核验课程) */
|
||||||
|
library_course_id?: string
|
||||||
/** 厂区(模板列:厂区,如 三厂) */
|
/** 厂区(模板列:厂区,如 三厂) */
|
||||||
plant: string
|
plant: string
|
||||||
/** 培训分类(模板列:分类,如 知识/技能/安全) */
|
/** 培训分类(模板列:分类,如 知识/技能/安全) */
|
||||||
@@ -185,7 +187,7 @@ export interface TrainingDemand {
|
|||||||
check_status: 'pending' | 'passed' | 'fixed'
|
check_status: 'pending' | 'passed' | 'fixed'
|
||||||
check_msg: string
|
check_msg: string
|
||||||
status: string
|
status: string
|
||||||
/** 联查展示字段:部门名称/讲师姓名/创建人姓名(提报人,联查 users 只读) */
|
/** 部门名称(列表联查 org_depts 只读;导入载荷另携带 Excel「部门」列原始值,000158 后端据此做导入人部门归属校验) */
|
||||||
dept_name?: string
|
dept_name?: string
|
||||||
lecturer_name?: string
|
lecturer_name?: string
|
||||||
submitter_name?: string
|
submitter_name?: string
|
||||||
@@ -1310,7 +1312,7 @@ export const NOTIFY_TEXT_TEMPLATES_RULE_KEY = 'notify_text_templates'
|
|||||||
export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集'
|
export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集'
|
||||||
export const DEFAULT_DEMAND_COLLECT_CONTENT =
|
export const DEFAULT_DEMAND_COLLECT_CONTENT =
|
||||||
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
|
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
|
||||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录和信智汇学院 → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||||
|
|
||||||
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
|
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
|
||||||
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
|
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
<span v-else class="avatar-placeholder">{{ userInitial }}</span>
|
<span v-else class="avatar-placeholder">{{ userInitial }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!showCollapsedLayout" class="user-info">
|
<div v-if="!showCollapsedLayout" class="user-info">
|
||||||
<!-- 多空间 / superuser:首行空间名,次行 username · 角色。单空间:昵称 + 邮箱。 -->
|
<!-- 多空间 / superuser:首行空间名,次行 姓名(未设置回落账号) · 角色。单空间:账号 + 姓名(未设置回落邮箱)。 -->
|
||||||
<template v-if="showTenantIdentityLine">
|
<template v-if="showTenantIdentityLine">
|
||||||
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
|
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
|
||||||
<div class="user-tenant-meta">
|
<div class="user-tenant-meta">
|
||||||
<span v-if="userName && userName !== activeTenantName" class="user-tenant-meta-name">{{ userName }}</span>
|
<span v-if="userDisplayLabel && userDisplayLabel !== activeTenantName" class="user-tenant-meta-name">{{ userDisplayLabel }}</span>
|
||||||
<span v-if="(userName && userName !== activeTenantName) && currentRoleLabel"
|
<span v-if="(userDisplayLabel && userDisplayLabel !== activeTenantName) && currentRoleLabel"
|
||||||
class="user-tenant-meta-sep">·</span>
|
class="user-tenant-meta-sep">·</span>
|
||||||
<t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" />
|
<t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" />
|
||||||
<span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span>
|
<span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span>
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<div class="user-name">{{ userName }}</div>
|
<div class="user-name">{{ userName }}</div>
|
||||||
<div class="user-email">{{ userEmail }}</div>
|
<div class="user-email">{{ userDisplayName }}</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -67,7 +67,7 @@
|
|||||||
</button>
|
</button>
|
||||||
</t-tooltip>
|
</t-tooltip>
|
||||||
</div>
|
</div>
|
||||||
<span v-if="userEmail" class="dropdown-user-email">{{ userEmail }}</span>
|
<span v-if="userDisplayName" class="dropdown-user-email">{{ userDisplayName }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -198,6 +198,7 @@ const menuVisible = ref(false)
|
|||||||
const userInfo = computed(() => ({
|
const userInfo = computed(() => ({
|
||||||
username: authStore.user?.username || t('common.defaultUser'),
|
username: authStore.user?.username || t('common.defaultUser'),
|
||||||
email: authStore.user?.email || 'user@example.com',
|
email: authStore.user?.email || 'user@example.com',
|
||||||
|
displayName: authStore.user?.display_name || '',
|
||||||
avatar: authStore.user?.avatar || '',
|
avatar: authStore.user?.avatar || '',
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -205,9 +206,16 @@ const userName = computed(() => userInfo.value.username)
|
|||||||
const userEmail = computed(() => userInfo.value.email)
|
const userEmail = computed(() => userInfo.value.email)
|
||||||
const userAvatar = computed(() => userInfo.value.avatar)
|
const userAvatar = computed(() => userInfo.value.avatar)
|
||||||
|
|
||||||
// 用户名首字母(用于无头像时显示)
|
// 侧栏第二行:工号式账号的 username 是工号,优先展示姓名;未设置姓名时回落邮箱
|
||||||
|
const userDisplayName = computed(() => userInfo.value.displayName || userInfo.value.email)
|
||||||
|
|
||||||
|
// 多空间身份行的姓名标签:优先姓名,未设置姓名时回落账号(工号/用户名)
|
||||||
|
const userDisplayLabel = computed(() => userInfo.value.displayName || userInfo.value.username)
|
||||||
|
|
||||||
|
// 用户名首字母(用于无头像时显示):优先取姓名首字(如「刘义亮」→「刘」),
|
||||||
|
// 未设置姓名时回落账号首字符
|
||||||
const userInitial = computed(() => {
|
const userInitial = computed(() => {
|
||||||
return userName.value.charAt(0).toUpperCase()
|
return userDisplayLabel.value.charAt(0).toUpperCase()
|
||||||
})
|
})
|
||||||
|
|
||||||
// 切换菜单显示
|
// 切换菜单显示
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
// ===== AIDO 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
// ===== 和信智汇学院 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
||||||
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入
|
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入。
|
||||||
|
// 品牌名由「AIDO」更名而来:中文六个字,字号/字距相应收窄以适配
|
||||||
|
// 260px 展开侧栏(logo 与搜索/折叠图标同行)与登录页左上角。
|
||||||
.aido-logo {
|
.aido-logo {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -16,12 +18,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&__text {
|
&__text {
|
||||||
font-family: 'Trebuchet MS', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', sans-serif;
|
||||||
font-size: 27px;
|
font-size: 19px;
|
||||||
line-height: 1.15;
|
line-height: 1.15;
|
||||||
font-weight: 800;
|
font-weight: 700;
|
||||||
font-style: italic;
|
white-space: nowrap;
|
||||||
letter-spacing: 2.5px;
|
letter-spacing: 1px;
|
||||||
background-image:
|
background-image:
|
||||||
linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.85) 50%, rgba(255, 255, 255, 0) 58%),
|
linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.85) 50%, rgba(255, 255, 255, 0) 58%),
|
||||||
linear-gradient(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%);
|
linear-gradient(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%);
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
<div class="aside_rail">
|
<div class="aside_rail">
|
||||||
<!-- 展开时:Logo + 搜索/折叠按钮同行 -->
|
<!-- 展开时:Logo + 搜索/折叠按钮同行 -->
|
||||||
<div class="logo_row" v-if="!uiStore.sidebarCollapsed">
|
<div class="logo_row" v-if="!uiStore.sidebarCollapsed">
|
||||||
<div class="logo_box" @click="router.push('/platform/knowledge-bases')" style="cursor: pointer;">
|
<div class="logo_box" @click="router.push('/platform/creatChat')" style="cursor: pointer;">
|
||||||
<span class="aido-logo" aria-label="AIDO" title="AIDO">
|
<span class="aido-logo" aria-label="和信智汇学院" title="和信智汇学院">
|
||||||
<span class="aido-logo__text">AIDO</span>
|
<span class="aido-logo__text">和信智汇学院</span>
|
||||||
<span class="aido-logo__dot"></span>
|
<span class="aido-logo__dot"></span>
|
||||||
</span>
|
</span>
|
||||||
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
|
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
|
||||||
@@ -605,12 +605,12 @@ const moreToolItems = computed<MenuItem[]>(() => {
|
|||||||
const items = MORE_TOOLS_ORDER
|
const items = MORE_TOOLS_ORDER
|
||||||
.map(path => all.find((item: MenuItem) => item.path === path))
|
.map(path => all.find((item: MenuItem) => item.path === path))
|
||||||
.filter((item): item is MenuItem => !!item);
|
.filter((item): item is MenuItem => !!item);
|
||||||
// 末位固定追加「配置中心」「职称角色」「组织架构」;「共享空间」还原至最底
|
// 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底
|
||||||
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
|
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
|
||||||
// 职称角色(000159):自「企业培训」分组迁入,置于配置中心之后
|
// 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由
|
||||||
const MEMBERS_TOOL_ITEM: MenuItem = { title: '职称角色', icon: 'training', path: 'training/members' };
|
// /platform/training/members 由路由重定向兜底
|
||||||
const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations');
|
const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations');
|
||||||
return [...items, RULES_TOOL_ITEM, MEMBERS_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
||||||
});
|
});
|
||||||
|
|
||||||
// 菜单图标统一映射:顶层项与「更多工具」子项共用
|
// 菜单图标统一映射:顶层项与「更多工具」子项共用
|
||||||
@@ -645,9 +645,9 @@ const TRAINING_TABS: { key: string; title: string }[] = [
|
|||||||
];
|
];
|
||||||
const TRAINING_GROUP_TITLE = '企业培训';
|
const TRAINING_GROUP_TITLE = '企业培训';
|
||||||
|
|
||||||
// 分组展开状态(记忆用户偏好,默认展开),交互与「更多工具」一致
|
// 分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
|
||||||
const TRAINING_OPEN_KEY = 'academy_training_open';
|
const TRAINING_OPEN_KEY = 'academy_training_open';
|
||||||
const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) !== 'false');
|
const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) === 'true');
|
||||||
const toggleTraining = () => {
|
const toggleTraining = () => {
|
||||||
trainingOpen.value = !trainingOpen.value;
|
trainingOpen.value = !trainingOpen.value;
|
||||||
localStorage.setItem(TRAINING_OPEN_KEY, String(trainingOpen.value));
|
localStorage.setItem(TRAINING_OPEN_KEY, String(trainingOpen.value));
|
||||||
@@ -669,9 +669,9 @@ const isTrainingTabActive = (tab: string): boolean => {
|
|||||||
return (String(route.params.tab || 'dashboard')) === tab;
|
return (String(route.params.tab || 'dashboard')) === tab;
|
||||||
};
|
};
|
||||||
|
|
||||||
// 「更多工具」分组展开状态(记忆用户偏好,默认展开)
|
// 「更多工具」分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
|
||||||
const MORE_TOOLS_OPEN_KEY = 'academy_moretools_open';
|
const MORE_TOOLS_OPEN_KEY = 'academy_moretools_open';
|
||||||
const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) !== 'false');
|
const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) === 'true');
|
||||||
const toggleMoreTools = () => {
|
const toggleMoreTools = () => {
|
||||||
moreToolsOpen.value = !moreToolsOpen.value;
|
moreToolsOpen.value = !moreToolsOpen.value;
|
||||||
localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value));
|
localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value));
|
||||||
|
|||||||
@@ -2970,7 +2970,7 @@ export default {
|
|||||||
haveAccount: 'Already have an account?',
|
haveAccount: 'Already have an account?',
|
||||||
backToLogin: 'Back to Login',
|
backToLogin: 'Back to Login',
|
||||||
loginHint: 'Sign in to continue, or create an account below if this is your first time.',
|
loginHint: 'Sign in to continue, or create an account below if this is your first time.',
|
||||||
firstTime: 'New to AIDO?',
|
firstTime: 'New to 和信智汇学院?',
|
||||||
registerSuccess: 'Registration successful. Please sign in',
|
registerSuccess: 'Registration successful. Please sign in',
|
||||||
registerFailed: 'Registration failed',
|
registerFailed: 'Registration failed',
|
||||||
subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade',
|
subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade',
|
||||||
|
|||||||
@@ -2970,7 +2970,7 @@ export default {
|
|||||||
haveAccount: 'すでにアカウントをお持ちですか?',
|
haveAccount: 'すでにアカウントをお持ちですか?',
|
||||||
backToLogin: 'ログインに戻る',
|
backToLogin: 'ログインに戻る',
|
||||||
loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。',
|
loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。',
|
||||||
firstTime: 'AIDOは初めてですか?',
|
firstTime: '和信智汇学院は初めてですか?',
|
||||||
registerSuccess: '登録が完了しました。ログインしてください',
|
registerSuccess: '登録が完了しました。ログインしてください',
|
||||||
registerFailed: '登録に失敗しました',
|
registerFailed: '登録に失敗しました',
|
||||||
subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード',
|
subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード',
|
||||||
|
|||||||
@@ -6262,7 +6262,7 @@ export default {
|
|||||||
haveAccount: '이미 계정이 있으신가요?',
|
haveAccount: '이미 계정이 있으신가요?',
|
||||||
backToLogin: '로그인으로 돌아가기',
|
backToLogin: '로그인으로 돌아가기',
|
||||||
loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.',
|
loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.',
|
||||||
firstTime: 'AIDO가 처음이신가요?',
|
firstTime: '和信智汇学院이 처음이신가요?',
|
||||||
registerSuccess: '가입이 완료되었습니다. 로그인해주세요',
|
registerSuccess: '가입이 완료되었습니다. 로그인해주세요',
|
||||||
registerFailed: '가입 실패',
|
registerFailed: '가입 실패',
|
||||||
subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드',
|
subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드',
|
||||||
|
|||||||
@@ -6262,7 +6262,7 @@ export default {
|
|||||||
haveAccount: 'Уже есть аккаунт?',
|
haveAccount: 'Уже есть аккаунт?',
|
||||||
backToLogin: 'Вернуться ко входу',
|
backToLogin: 'Вернуться ко входу',
|
||||||
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
|
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
|
||||||
firstTime: 'Впервые в AIDO?',
|
firstTime: 'Впервые в 和信智汇学院?',
|
||||||
registerSuccess: 'Регистрация завершена. Войдите в систему',
|
registerSuccess: 'Регистрация завершена. Войдите в систему',
|
||||||
registerFailed: 'Ошибка регистрации',
|
registerFailed: 'Ошибка регистрации',
|
||||||
subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ',
|
subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ',
|
||||||
|
|||||||
@@ -6263,7 +6263,7 @@ export default {
|
|||||||
haveAccount: '已有账户?',
|
haveAccount: '已有账户?',
|
||||||
backToLogin: '返回登录',
|
backToLogin: '返回登录',
|
||||||
loginHint: '登录以继续使用;首次使用请在下方创建账户。',
|
loginHint: '登录以继续使用;首次使用请在下方创建账户。',
|
||||||
firstTime: '首次使用 AIDO?',
|
firstTime: '首次使用 和信智汇学院?',
|
||||||
registerSuccess: '注册成功,请登录',
|
registerSuccess: '注册成功,请登录',
|
||||||
registerFailed: '注册失败',
|
registerFailed: '注册失败',
|
||||||
subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级',
|
subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级',
|
||||||
|
|||||||
@@ -6263,7 +6263,7 @@ export default {
|
|||||||
haveAccount: '已有帳戶?',
|
haveAccount: '已有帳戶?',
|
||||||
backToLogin: '返回登入',
|
backToLogin: '返回登入',
|
||||||
loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。',
|
loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。',
|
||||||
firstTime: '首次使用 AIDO?',
|
firstTime: '首次使用 和信智汇学院?',
|
||||||
registerSuccess: '註冊成功,請登入',
|
registerSuccess: '註冊成功,請登入',
|
||||||
registerFailed: '註冊失敗',
|
registerFailed: '註冊失敗',
|
||||||
subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級',
|
subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級',
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
|
|||||||
to.path === '/' ||
|
to.path === '/' ||
|
||||||
to.path === '/platform' ||
|
to.path === '/platform' ||
|
||||||
to.path === '/platform/knowledge-bases' ||
|
to.path === '/platform/knowledge-bases' ||
|
||||||
|
to.path === '/platform/creatChat' ||
|
||||||
to.name === 'knowledgeBaseList'
|
to.name === 'knowledgeBaseList'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -46,7 +47,8 @@ const router = createRouter({
|
|||||||
routes: [
|
routes: [
|
||||||
{
|
{
|
||||||
path: "/",
|
path: "/",
|
||||||
redirect: "/platform/knowledge-bases",
|
// 登录用户默认打开 AI 对话页(首页口径,与登录成功跳转一致)
|
||||||
|
redirect: "/platform/creatChat",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: "/login",
|
path: "/login",
|
||||||
@@ -94,7 +96,7 @@ const router = createRouter({
|
|||||||
{
|
{
|
||||||
path: "/platform",
|
path: "/platform",
|
||||||
name: "Platform",
|
name: "Platform",
|
||||||
redirect: "/platform/knowledge-bases",
|
redirect: "/platform/creatChat",
|
||||||
component: () => import("../views/platform/index.vue"),
|
component: () => import("../views/platform/index.vue"),
|
||||||
meta: { requiresInit: true, requiresAuth: true },
|
meta: { requiresInit: true, requiresAuth: true },
|
||||||
children: [
|
children: [
|
||||||
@@ -156,12 +158,18 @@ const router = createRouter({
|
|||||||
meta: { requiresInit: true, requiresAuth: true }
|
meta: { requiresInit: true, requiresAuth: true }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/职称角色/配置中心)
|
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/配置中心)
|
||||||
// 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。
|
// 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。
|
||||||
path: "training",
|
path: "training",
|
||||||
name: "training",
|
name: "training",
|
||||||
redirect: "/platform/training/dashboard"
|
redirect: "/platform/training/dashboard"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// 职称角色页已并入「组织架构」页维护(员工/角色/企微账号一处维护),
|
||||||
|
// 旧链接与书签兜底重定向。
|
||||||
|
path: "training/members",
|
||||||
|
redirect: "/platform/org-center"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: "training/:tab",
|
path: "training/:tab",
|
||||||
name: "trainingTab",
|
name: "trainingTab",
|
||||||
@@ -368,7 +376,7 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (authStore.hasValidTenant) {
|
if (authStore.hasValidTenant) {
|
||||||
next('/platform/knowledge-bases')
|
next('/platform/creatChat')
|
||||||
} else {
|
} else {
|
||||||
next()
|
next()
|
||||||
}
|
}
|
||||||
@@ -377,9 +385,9 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
|
|
||||||
// 如果访问的是登录页面或初始化页面,直接放行
|
// 如果访问的是登录页面或初始化页面,直接放行
|
||||||
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
|
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
|
||||||
// 如果已登录用户访问登录页面,重定向到知识库列表页面
|
// 如果已登录用户访问登录页面,重定向到首页(AI 对话)
|
||||||
if (to.path === '/login' && authStore.isLoggedIn) {
|
if (to.path === '/login' && authStore.isLoggedIn) {
|
||||||
next(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
next(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next()
|
next()
|
||||||
@@ -431,7 +439,7 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined
|
const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined
|
||||||
if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) {
|
if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) {
|
||||||
MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable'))
|
MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable'))
|
||||||
next('/platform/knowledge-bases')
|
next('/platform/creatChat')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,7 +449,7 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
// the bounce. This is UI-only; the server enforces the real check.
|
// the bounce. This is UI-only; the server enforces the real check.
|
||||||
if (to.meta.requiresSystemAdmin === true) {
|
if (to.meta.requiresSystemAdmin === true) {
|
||||||
if (!authStore.isSystemAdmin) {
|
if (!authStore.isSystemAdmin) {
|
||||||
next('/platform/knowledge-bases')
|
next('/platform/creatChat')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3021,8 +3021,11 @@ const removeStarterSuggestion = (index: number) => {
|
|||||||
formData.value.config.question_suggestions.starters.items.splice(index, 1);
|
formData.value.config.question_suggestions.starters.items.splice(index, 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
|
||||||
|
// 仅在字段为空时补值,绝不覆盖用户已选;编辑态补默认可修复存量空模型智能体,
|
||||||
|
// 免去「模型必填」手动配置(与后端 create 兜底同规则)。
|
||||||
const applyDefaultModelsIfEmpty = () => {
|
const applyDefaultModelsIfEmpty = () => {
|
||||||
if (props.mode !== 'create' || !formData.value) return
|
if (!formData.value) return
|
||||||
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
||||||
const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
|
const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
|
||||||
if (!formData.value.config.model_id && chatModelId) {
|
if (!formData.value.config.model_id && chatModelId) {
|
||||||
@@ -3698,6 +3701,8 @@ watch(() => props.visible, async (val) => {
|
|||||||
// Display inherited defaults for all agents without persisting a copy.
|
// Display inherited defaults for all agents without persisting a copy.
|
||||||
fillBuiltinAgentDefaults();
|
fillBuiltinAgentDefaults();
|
||||||
void loadAgentIntegrationCounts(agentData.id);
|
void loadAgentIntegrationCounts(agentData.id);
|
||||||
|
// 编辑态同样补默认模型(仅空字段):存量空模型智能体不再被「模型必填」卡住
|
||||||
|
applyDefaultModelsIfEmpty()
|
||||||
} else {
|
} else {
|
||||||
// 创建新智能体,使用系统默认值
|
// 创建新智能体,使用系统默认值
|
||||||
storedToolNames.value = [];
|
storedToolNames.value = [];
|
||||||
|
|||||||
@@ -97,8 +97,8 @@
|
|||||||
|
|
||||||
<!-- Logo - Top Left -->
|
<!-- Logo - Top Left -->
|
||||||
<a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')">
|
<a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')">
|
||||||
<span class="aido-logo" aria-label="AIDO">
|
<span class="aido-logo" aria-label="和信智汇学院">
|
||||||
<span class="aido-logo__text">AIDO</span>
|
<span class="aido-logo__text">和信智汇学院</span>
|
||||||
<span class="aido-logo__dot"></span>
|
<span class="aido-logo__dot"></span>
|
||||||
</span>
|
</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -611,7 +611,7 @@ const persistLoginResponse = async (response: any, skipRedirect = false) => {
|
|||||||
await authStore.refreshFromAuthMe()
|
await authStore.refreshFromAuthMe()
|
||||||
await nextTick()
|
await nextTick()
|
||||||
if (skipRedirect) return
|
if (skipRedirect) return
|
||||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||||
}
|
}
|
||||||
|
|
||||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||||
@@ -694,7 +694,7 @@ const acceptAndEnter = async (token: string) => {
|
|||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
loading.value = false
|
||||||
await nextTick()
|
await nextTick()
|
||||||
router.replace('/platform/knowledge-bases')
|
router.replace('/platform/creatChat')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -852,7 +852,7 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (authStore.isLoggedIn) {
|
if (authStore.isLoggedIn) {
|
||||||
router.replace('/platform/knowledge-bases')
|
router.replace('/platform/creatChat')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -889,8 +889,11 @@ const kbCreateNeedsEmbedding = computed(() => {
|
|||||||
return Boolean(s?.vectorEnabled || s?.keywordEnabled)
|
return Boolean(s?.vectorEnabled || s?.keywordEnabled)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 模型自动配置(新建/编辑通用):默认模型优先,无默认取该类型第一个 active。
|
||||||
|
// 仅在字段为空时补值,不覆盖用户已选;与后端 CreateKnowledgeBase 的默认兜底
|
||||||
|
// 同规则,编辑态补默认可修复存量未绑模型的知识库。
|
||||||
const applyDefaultModelsIfEmpty = () => {
|
const applyDefaultModelsIfEmpty = () => {
|
||||||
if (!formData.value || editorMode.value !== 'create') return
|
if (!formData.value) return
|
||||||
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
|
||||||
const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding')
|
const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding')
|
||||||
if (!formData.value.modelConfig.llmModelId && chatModelId) {
|
if (!formData.value.modelConfig.llmModelId && chatModelId) {
|
||||||
@@ -1936,6 +1939,8 @@ watch(() => props.visible, async (newVal) => {
|
|||||||
// 根据模式加载数据
|
// 根据模式加载数据
|
||||||
if (props.mode === 'edit' && targetKbId) {
|
if (props.mode === 'edit' && targetKbId) {
|
||||||
await loadKBData(targetKbId, generation)
|
await loadKBData(targetKbId, generation)
|
||||||
|
// 编辑态同样补默认模型(仅空字段):存量未绑模型的知识库不再要求手动选择
|
||||||
|
applyDefaultModelsIfEmpty()
|
||||||
} else {
|
} else {
|
||||||
// 创建模式:初始化空表单,并预填空间默认存储引擎
|
// 创建模式:初始化空表单,并预填空间默认存储引擎
|
||||||
formData.value = initFormData(props.initialType || 'document')
|
formData.value = initFormData(props.initialType || 'document')
|
||||||
|
|||||||
@@ -34,7 +34,32 @@
|
|||||||
<div class="panel-box org-layout__employees">
|
<div class="panel-box org-layout__employees">
|
||||||
<div class="panel-box__header">
|
<div class="panel-box__header">
|
||||||
<span class="panel-box__title">员工档案</span>
|
<span class="panel-box__title">员工档案</span>
|
||||||
<div style="display: flex; gap: 8px">
|
<!-- 自「职称角色」页迁入:提示 + OA 同步入口(管理角色可见) -->
|
||||||
|
<div class="org-employees__actions">
|
||||||
|
<span class="org-employees__hint">员工与部门在本页统一维护,职称角色与企微账号可直接配置</span>
|
||||||
|
<t-input
|
||||||
|
v-model="keyword"
|
||||||
|
class="org-employees__search"
|
||||||
|
clearable
|
||||||
|
placeholder="按姓名 / 工号 / 部门查找"
|
||||||
|
@enter="loadEmployees"
|
||||||
|
@clear="loadEmployees"
|
||||||
|
>
|
||||||
|
<template #prefixIcon><t-icon name="search" /></template>
|
||||||
|
</t-input>
|
||||||
|
<t-button
|
||||||
|
v-if="canManage"
|
||||||
|
variant="outline"
|
||||||
|
theme="primary"
|
||||||
|
:loading="syncing"
|
||||||
|
class="oa-sync-btn"
|
||||||
|
@click="onPreviewSync"
|
||||||
|
>
|
||||||
|
从OA同步企微账号
|
||||||
|
</t-button>
|
||||||
|
<!-- 收编归属空间:仅空间 Owner 可见/可操作(后端路由 Owner 限定),
|
||||||
|
把登录落在个人空间的成员默认落点改回本空间 -->
|
||||||
|
<t-button v-if="canAdopt" variant="outline" @click="openAdopt">收编到本空间</t-button>
|
||||||
<t-button variant="outline" @click="openPicker">从平台用户添加</t-button>
|
<t-button variant="outline" @click="openPicker">从平台用户添加</t-button>
|
||||||
<t-button theme="primary" @click="importVisible = true">批量导入</t-button>
|
<t-button theme="primary" @click="importVisible = true">批量导入</t-button>
|
||||||
</div>
|
</div>
|
||||||
@@ -46,6 +71,12 @@
|
|||||||
</t-tooltip>
|
</t-tooltip>
|
||||||
</template>
|
</template>
|
||||||
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
||||||
|
<template #wecom_userid="{ row }">
|
||||||
|
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
|
||||||
|
</template>
|
||||||
|
<template #roles="{ row }">
|
||||||
|
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
|
||||||
|
</template>
|
||||||
<template #status="{ row }">
|
<template #status="{ row }">
|
||||||
<t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag>
|
<t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag>
|
||||||
<t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag>
|
<t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag>
|
||||||
@@ -54,6 +85,8 @@
|
|||||||
<template #op="{ row }">
|
<template #op="{ row }">
|
||||||
<div class="op-group">
|
<div class="op-group">
|
||||||
<t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button>
|
<t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button>
|
||||||
|
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
|
||||||
|
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</t-table>
|
</t-table>
|
||||||
@@ -150,6 +183,106 @@
|
|||||||
<t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button>
|
<t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button>
|
||||||
</template>
|
</template>
|
||||||
</t-dialog>
|
</t-dialog>
|
||||||
|
|
||||||
|
<!-- 绑定企微账号(培训提醒推送目标;自职称角色页迁入) -->
|
||||||
|
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
|
||||||
|
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
|
||||||
|
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
|
||||||
|
<template #footer>
|
||||||
|
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
|
||||||
|
</template>
|
||||||
|
</t-dialog>
|
||||||
|
|
||||||
|
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
|
||||||
|
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
|
||||||
|
<template v-if="syncSummary">
|
||||||
|
<div class="sync-stats">
|
||||||
|
<span>本地员工 {{ syncSummary.local_candidates }}</span>
|
||||||
|
<span>OA 命中 {{ syncSummary.local_matched }}</span>
|
||||||
|
<span>已一致 {{ syncSummary.already_bound }}</span>
|
||||||
|
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
|
||||||
|
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
|
||||||
|
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
|
||||||
|
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
|
||||||
|
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
|
||||||
|
{{ cf.employee_no }} {{ cf.user_name || '' }}:
|
||||||
|
{{ conflictText(cf) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="syncSummary.would_update" class="sync-section">
|
||||||
|
<div class="sync-section__title">将写入(最多展示 20 条)</div>
|
||||||
|
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
|
||||||
|
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
|
||||||
|
无需更新:绑定已一致或 OA 无匹配数据。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="sync-footer">
|
||||||
|
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
|
||||||
|
theme="primary" :loading="syncing" @click="onApplySync">
|
||||||
|
确认写入
|
||||||
|
</t-button>
|
||||||
|
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</t-dialog>
|
||||||
|
|
||||||
|
<!-- 设置职称角色(自职称角色页迁入;绑定写 module_key='training') -->
|
||||||
|
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
|
||||||
|
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
|
||||||
|
<t-select v-model="roleSelection" multiple style="width: 100%">
|
||||||
|
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
|
||||||
|
</t-select>
|
||||||
|
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
|
||||||
|
<template #footer>
|
||||||
|
<t-button theme="primary" :loading="savingRoles" @click="onSaveRoles">保存</t-button>
|
||||||
|
</template>
|
||||||
|
</t-dialog>
|
||||||
|
|
||||||
|
<!-- 收编到本空间:把登录落在个人空间的成员的默认落点改回本空间。
|
||||||
|
预览(归属空间不在本空间的活跃成员)→ 确认收编,与 OA 同步同两段式交互 -->
|
||||||
|
<t-dialog v-model:visible="adoptVisible" header="收编成员到本空间" width="680" :footer="false">
|
||||||
|
<div class="form-hint adopt-hint">
|
||||||
|
名单为「归属空间不在本空间」的活跃成员(首次登录自动开通个人空间后,登录会落进个人空间,看不到本空间维护的组织架构与培训数据)。
|
||||||
|
收编后其默认登录空间改为本空间,下次登录起直接进入本空间;成员关系、角色与个人空间数据均不变,成员仍可随时用左下角空间切换器改回。
|
||||||
|
</div>
|
||||||
|
<template v-if="adoptLoaded">
|
||||||
|
<div v-if="!adoptList.length" class="sync-section">
|
||||||
|
没有可收编成员:所有成员的登录默认空间都已指向本空间。
|
||||||
|
</div>
|
||||||
|
<template v-else>
|
||||||
|
<t-table
|
||||||
|
:data="adoptList"
|
||||||
|
:columns="adoptColumns"
|
||||||
|
row-key="id"
|
||||||
|
size="small"
|
||||||
|
max-height="360"
|
||||||
|
>
|
||||||
|
<template #display_name="{ row }">{{ row.display_name || '-' }}</template>
|
||||||
|
<template #home="{ row }">
|
||||||
|
{{ row.home_tenant_name || (row.home_tenant_id ? `空间 ${row.home_tenant_id}` : '无归属空间') }}
|
||||||
|
</template>
|
||||||
|
<template #in_roster="{ row }">
|
||||||
|
<t-tag v-if="row.in_roster" theme="success" variant="light" size="small">在名册</t-tag>
|
||||||
|
<t-tag v-else theme="default" variant="light" size="small">未入册</t-tag>
|
||||||
|
</template>
|
||||||
|
</t-table>
|
||||||
|
<div class="sync-footer">
|
||||||
|
<t-button variant="outline" @click="adoptVisible = false">关闭</t-button>
|
||||||
|
<t-button theme="primary" :loading="adopting" @click="onAdopt">
|
||||||
|
全部收编({{ adoptList.length }})
|
||||||
|
</t-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</t-dialog>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -157,26 +290,48 @@
|
|||||||
import { computed, onMounted, ref, watch } from 'vue'
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
import { MessagePlugin } from 'tdesign-vue-next'
|
import { MessagePlugin } from 'tdesign-vue-next'
|
||||||
import {
|
import {
|
||||||
|
adoptHomeTenant,
|
||||||
|
applyOrgWecomSync,
|
||||||
deleteDept,
|
deleteDept,
|
||||||
importEmployees,
|
importEmployees,
|
||||||
|
listAdoptableUsers,
|
||||||
listDepts,
|
listDepts,
|
||||||
listEmployees,
|
listEmployees,
|
||||||
listPlatformUsers,
|
listPlatformUsers,
|
||||||
|
ORG_MODULE_TRAINING,
|
||||||
|
previewOrgWecomSync,
|
||||||
saveDept,
|
saveDept,
|
||||||
updateEmployee,
|
updateEmployee,
|
||||||
|
updateOrgEmployeeRoles,
|
||||||
|
updateOrgEmployeeWecomUserid,
|
||||||
|
type OrgAdoptableUser,
|
||||||
type OrgDept,
|
type OrgDept,
|
||||||
type OrgEmployee,
|
type OrgEmployee,
|
||||||
type OrgPlatformUser,
|
type OrgPlatformUser,
|
||||||
} from '@/api/org-center'
|
} from '@/api/org-center'
|
||||||
import { unwrap } from '@/api/training'
|
import {
|
||||||
|
expandRoles,
|
||||||
|
fetchRoleDict,
|
||||||
|
getMyProfile,
|
||||||
|
roleLabelOf,
|
||||||
|
unwrap,
|
||||||
|
type TrainingRoleDef,
|
||||||
|
type WecomSyncConflict,
|
||||||
|
type WecomSyncSummary,
|
||||||
|
} from '@/api/training'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||||
|
|
||||||
|
const authStore = useAuthStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
const depts = ref<OrgDept[]>([])
|
const depts = ref<OrgDept[]>([])
|
||||||
const employees = ref<OrgEmployee[]>([])
|
const employees = ref<OrgEmployee[]>([])
|
||||||
const platformUsers = ref<OrgPlatformUser[]>([])
|
const platformUsers = ref<OrgPlatformUser[]>([])
|
||||||
|
|
||||||
|
// 员工查找(需求:按名称/工号/部门);keyword 走后端 ListEmployees 的过滤。
|
||||||
|
const keyword = ref('')
|
||||||
|
|
||||||
const deptFormVisible = ref(false)
|
const deptFormVisible = ref(false)
|
||||||
const importVisible = ref(false)
|
const importVisible = ref(false)
|
||||||
// id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。
|
// id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。
|
||||||
@@ -193,6 +348,174 @@ const pickerPost = ref('')
|
|||||||
const employeeFormVisible = ref(false)
|
const employeeFormVisible = ref(false)
|
||||||
const employeeForm = ref({ id: '', user_name: '', employee_no: '', dept_id: '', post: '', status: 'active' })
|
const employeeForm = ref({ id: '', user_name: '', employee_no: '', dept_id: '', post: '', status: 'active' })
|
||||||
|
|
||||||
|
// ---- 职称角色 / 企微账号(自培训域「职称角色」页迁入) ----
|
||||||
|
|
||||||
|
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
|
||||||
|
const roleDict = ref<TrainingRoleDef[]>([])
|
||||||
|
// 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护)
|
||||||
|
const rawRoles = ref<string[]>([])
|
||||||
|
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
|
||||||
|
const canManage = computed(
|
||||||
|
() => authStore.hasRole('admin') || myRoles.value.some((r) => r === 'hr' || r === 'exec'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const rolesVisible = ref(false)
|
||||||
|
const activeEmployee = ref<OrgEmployee | null>(null)
|
||||||
|
const roleSelection = ref<string[]>([])
|
||||||
|
const savingRoles = ref(false)
|
||||||
|
|
||||||
|
const wecomVisible = ref(false)
|
||||||
|
const activeWecomEmployee = ref<OrgEmployee | null>(null)
|
||||||
|
const wecomInput = ref('')
|
||||||
|
const savingWecom = ref(false)
|
||||||
|
|
||||||
|
// OA 同步(工号 → 企微 userid,预览→写入两段式)
|
||||||
|
const syncVisible = ref(false)
|
||||||
|
const syncing = ref(false)
|
||||||
|
const syncSummary = ref<WecomSyncSummary | null>(null)
|
||||||
|
|
||||||
|
const conflictText = (cf: WecomSyncConflict) => {
|
||||||
|
switch (cf.reason) {
|
||||||
|
case 'duplicate_workcode_in_oa':
|
||||||
|
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
|
||||||
|
case 'bound_to_different_userid':
|
||||||
|
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
|
||||||
|
case 'userid_occupied':
|
||||||
|
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
|
||||||
|
default:
|
||||||
|
return cf.reason
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onPreviewSync = async () => {
|
||||||
|
syncing.value = true
|
||||||
|
try {
|
||||||
|
const res = await previewOrgWecomSync()
|
||||||
|
syncSummary.value = unwrap(res) ?? null
|
||||||
|
syncVisible.value = true
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
|
||||||
|
} finally {
|
||||||
|
syncing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onApplySync = async () => {
|
||||||
|
syncing.value = true
|
||||||
|
try {
|
||||||
|
const res = await applyOrgWecomSync()
|
||||||
|
const summary = unwrap(res)
|
||||||
|
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
|
||||||
|
syncVisible.value = false
|
||||||
|
loadEmployees()
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || '写入失败')
|
||||||
|
} finally {
|
||||||
|
syncing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 收编到本空间(归属空间=登录默认落点;后端 Owner 限定) ----
|
||||||
|
|
||||||
|
// 仅空间 Owner 可见(与后端 g.Owner() 路由口径对齐;localStorage 只是渲染参考,
|
||||||
|
// 实际权限以服务端为准,越权点击会收到 403)。
|
||||||
|
const canAdopt = computed(() => authStore.hasRole('owner'))
|
||||||
|
const adoptVisible = ref(false)
|
||||||
|
const adoptLoaded = ref(false)
|
||||||
|
const adopting = ref(false)
|
||||||
|
const adoptList = ref<OrgAdoptableUser[]>([])
|
||||||
|
|
||||||
|
const adoptColumns = [
|
||||||
|
{ colKey: 'username', title: '工号', width: 100 },
|
||||||
|
{ colKey: 'display_name', title: '姓名', width: 110 },
|
||||||
|
{ colKey: 'email', title: '邮箱', minWidth: 160, ellipsis: true },
|
||||||
|
{ colKey: 'home', title: '当前归属空间(登录落点)', width: 180 },
|
||||||
|
{ colKey: 'in_roster', title: '名册', width: 80 },
|
||||||
|
]
|
||||||
|
|
||||||
|
const openAdopt = async () => {
|
||||||
|
adoptVisible.value = true
|
||||||
|
adoptLoaded.value = false
|
||||||
|
adoptList.value = []
|
||||||
|
try {
|
||||||
|
const res = await listAdoptableUsers()
|
||||||
|
adoptList.value = unwrap(res) || []
|
||||||
|
adoptLoaded.value = true
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || '加载可收编成员失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onAdopt = async () => {
|
||||||
|
if (!adoptList.value.length) return
|
||||||
|
adopting.value = true
|
||||||
|
try {
|
||||||
|
const res = await adoptHomeTenant(adoptList.value.map((u) => u.id))
|
||||||
|
const result = unwrap(res)
|
||||||
|
const skipped = result?.skipped || []
|
||||||
|
MessagePlugin.success(`已收编 ${result?.adopted ?? 0} 名成员,自下次登录起默认进入本空间`)
|
||||||
|
// 预览与收编之间成员关系可能变化(被移出/停用),逐条原因只提示首条避免刷屏。
|
||||||
|
if (skipped.length) {
|
||||||
|
const first = skipped[0]
|
||||||
|
MessagePlugin.warning(
|
||||||
|
`${skipped.length} 名成员被跳过:如 ${first.username} ${first.reason}${skipped.length > 1 ? ' 等' : ''}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
adoptVisible.value = false
|
||||||
|
loadEmployees()
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || '收编失败')
|
||||||
|
} finally {
|
||||||
|
adopting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openRoles = (row: OrgEmployee) => {
|
||||||
|
activeEmployee.value = row
|
||||||
|
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
|
||||||
|
rolesVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSaveRoles = async () => {
|
||||||
|
if (!activeEmployee.value) return
|
||||||
|
savingRoles.value = true
|
||||||
|
try {
|
||||||
|
// 学员角色为全员隐式默认,保存时总是带回去(与后端口径一致)。
|
||||||
|
await updateOrgEmployeeRoles(activeEmployee.value.id, [...roleSelection.value, 'trainee'])
|
||||||
|
MessagePlugin.success('角色已更新')
|
||||||
|
rolesVisible.value = false
|
||||||
|
loadEmployees()
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||||
|
} finally {
|
||||||
|
savingRoles.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openWecom = (row: OrgEmployee) => {
|
||||||
|
activeWecomEmployee.value = row
|
||||||
|
wecomInput.value = row.wecom_userid || ''
|
||||||
|
wecomVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSaveWecom = async () => {
|
||||||
|
if (!activeWecomEmployee.value) return
|
||||||
|
savingWecom.value = true
|
||||||
|
try {
|
||||||
|
await updateOrgEmployeeWecomUserid(activeWecomEmployee.value.id, wecomInput.value.trim())
|
||||||
|
MessagePlugin.success('企微账号已更新')
|
||||||
|
wecomVisible.value = false
|
||||||
|
loadEmployees()
|
||||||
|
} catch (err: any) {
|
||||||
|
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||||
|
} finally {
|
||||||
|
savingWecom.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
|
||||||
|
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
|
||||||
|
|
||||||
const deptColumns = [
|
const deptColumns = [
|
||||||
{ colKey: 'name', title: '部门名称' },
|
{ colKey: 'name', title: '部门名称' },
|
||||||
{ colKey: 'code', title: '编码', width: 140 },
|
{ colKey: 'code', title: '编码', width: 140 },
|
||||||
@@ -200,15 +523,18 @@ const deptColumns = [
|
|||||||
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const employeeColumns = [
|
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
|
||||||
|
const employeeColumns = computed(() => [
|
||||||
{ colKey: 'employee_no', title: '工号', width: 90 },
|
{ colKey: 'employee_no', title: '工号', width: 90 },
|
||||||
{ colKey: 'user_name', title: '姓名' },
|
{ colKey: 'user_name', title: '姓名', width: 110 },
|
||||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
{ colKey: 'dept_name', title: '部门', width: 100 },
|
||||||
{ colKey: 'post', title: '岗位', width: 140 },
|
{ colKey: 'post', title: '岗位', width: 120 },
|
||||||
{ colKey: 'status', title: '状态', width: 76 },
|
{ colKey: 'wecom_userid', title: '企微账号', width: 110 },
|
||||||
// 列总宽超出面板宽度时固定在右侧,避免"修改"按钮被横向滚动挤出可视区
|
{ colKey: 'roles', title: '职称角色' },
|
||||||
{ colKey: 'op', title: '操作', width: 84, fixed: 'right' },
|
{ colKey: 'status', title: '状态', width: 70 },
|
||||||
]
|
// 列总宽超出面板宽度时固定在右侧,避免操作按钮被横向滚动挤出可视区
|
||||||
|
{ colKey: 'op', title: '操作', width: canManage.value ? 200 : 84, fixed: 'right' },
|
||||||
|
])
|
||||||
|
|
||||||
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
||||||
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。
|
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。
|
||||||
@@ -249,23 +575,53 @@ watch(pickerUserIds, (ids) => {
|
|||||||
if (deptId) pickerDeptId.value = deptId
|
if (deptId) pickerDeptId.value = deptId
|
||||||
})
|
})
|
||||||
|
|
||||||
const loadAll = async () => {
|
// 员工列表:module_key='training' 联查职称角色展示;keyword 按姓名/工号/部门过滤。
|
||||||
|
const loadEmployees = async () => {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
const e = await listEmployees({
|
||||||
const [d, e, u] = await Promise.all([
|
module_key: ORG_MODULE_TRAINING,
|
||||||
listDepts(),
|
keyword: keyword.value.trim() || undefined,
|
||||||
listEmployees({ page_size: 500 }),
|
page_size: 500,
|
||||||
listPlatformUsers().catch(() => null),
|
})
|
||||||
])
|
|
||||||
depts.value = unwrap(d) || []
|
|
||||||
employees.value = unwrap(e)?.items || []
|
employees.value = unwrap(e)?.items || []
|
||||||
platformUsers.value = unwrap(u) || []
|
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
loading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 输入防抖触发查找(enter/clear 立即触发由模板回调完成)
|
||||||
|
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
watch(keyword, () => {
|
||||||
|
clearTimeout(searchTimer)
|
||||||
|
searchTimer = setTimeout(() => loadEmployees(), 300)
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadAll = async () => {
|
||||||
|
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
||||||
|
const [d, u] = await Promise.all([
|
||||||
|
listDepts(),
|
||||||
|
listPlatformUsers().catch(() => null),
|
||||||
|
])
|
||||||
|
depts.value = unwrap(d) || []
|
||||||
|
platformUsers.value = unwrap(u) || []
|
||||||
|
await loadEmployees()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 本人职称角色(人事/经理/空间管理员可维护;口径与培训页 canManageConfig 一致)
|
||||||
|
const loadProfile = async () => {
|
||||||
|
try {
|
||||||
|
const res = await getMyProfile() as any
|
||||||
|
const member: OrgEmployee | undefined = res?.data?.data || res?.data
|
||||||
|
if (member) {
|
||||||
|
rawRoles.value = (member.roles as unknown as string[]) || ['trainee']
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 取不到档案按纯学员兜底:仅隐藏维护入口,不影响页面其余功能。
|
||||||
|
rawRoles.value = ['trainee']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const openCreateDept = () => {
|
const openCreateDept = () => {
|
||||||
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
|
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
|
||||||
deptFormVisible.value = true
|
deptFormVisible.value = true
|
||||||
@@ -349,7 +705,7 @@ const onPickImport = async () => {
|
|||||||
pickerVisible.value = false
|
pickerVisible.value = false
|
||||||
pickerUserIds.value = []
|
pickerUserIds.value = []
|
||||||
pickerDeptId.value = ''
|
pickerDeptId.value = ''
|
||||||
loadAll()
|
loadEmployees()
|
||||||
} catch {
|
} catch {
|
||||||
MessagePlugin.error('添加失败')
|
MessagePlugin.error('添加失败')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -385,7 +741,7 @@ const onSaveEmployee = async () => {
|
|||||||
})
|
})
|
||||||
MessagePlugin.success('员工档案已更新')
|
MessagePlugin.success('员工档案已更新')
|
||||||
employeeFormVisible.value = false
|
employeeFormVisible.value = false
|
||||||
loadAll()
|
loadEmployees()
|
||||||
} catch {
|
} catch {
|
||||||
MessagePlugin.error('保存失败')
|
MessagePlugin.error('保存失败')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -430,7 +786,7 @@ const onImport = async () => {
|
|||||||
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
|
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
|
||||||
importVisible.value = false
|
importVisible.value = false
|
||||||
importText.value = ''
|
importText.value = ''
|
||||||
loadAll()
|
loadEmployees()
|
||||||
} catch {
|
} catch {
|
||||||
MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
|
MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -438,7 +794,13 @@ const onImport = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(loadAll)
|
onMounted(() => {
|
||||||
|
loadAll()
|
||||||
|
loadProfile()
|
||||||
|
fetchRoleDict().then((d) => {
|
||||||
|
roleDict.value = d
|
||||||
|
})
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="less" scoped>
|
<style lang="less" scoped>
|
||||||
@@ -498,4 +860,55 @@ onMounted(loadAll)
|
|||||||
word-break: break-all;
|
word-break: break-all;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
}
|
}
|
||||||
|
// 员工面板头部工具条:提示文案 + 查找框 + 动作按钮(窄屏折行)
|
||||||
|
.org-employees__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.org-employees__hint {
|
||||||
|
color: var(--td-text-color-placeholder);
|
||||||
|
font-size: var(--app-text-sm);
|
||||||
|
}
|
||||||
|
.org-employees__search {
|
||||||
|
width: 200px;
|
||||||
|
}
|
||||||
|
.oa-sync-btn {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.role-tag {
|
||||||
|
margin-right: 4px;
|
||||||
|
}
|
||||||
|
.wecom-missing {
|
||||||
|
color: var(--td-text-color-placeholder);
|
||||||
|
}
|
||||||
|
.sync-stats {
|
||||||
|
display: flex;
|
||||||
|
gap: 14px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
|
||||||
|
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
|
||||||
|
}
|
||||||
|
.sync-section {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
max-height: 180px;
|
||||||
|
overflow: auto;
|
||||||
|
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
|
||||||
|
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
|
||||||
|
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
|
||||||
|
}
|
||||||
|
.sync-footer {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
// 收编弹窗说明文案
|
||||||
|
.adopt-hint {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -57,14 +57,6 @@
|
|||||||
active
|
active
|
||||||
fill-height
|
fill-height
|
||||||
/>
|
/>
|
||||||
<DocumentPreview
|
|
||||||
v-else-if="current && isDoc(current)"
|
|
||||||
:knowledge-id="current.knowledge_id"
|
|
||||||
:file-type="previewKind(current)"
|
|
||||||
:file-name="current.name"
|
|
||||||
active
|
|
||||||
fill-height
|
|
||||||
/>
|
|
||||||
<t-empty
|
<t-empty
|
||||||
v-else-if="current"
|
v-else-if="current"
|
||||||
class="preview-empty"
|
class="preview-empty"
|
||||||
@@ -209,7 +201,6 @@ const previewKind = (m: TrainingMaterial) => {
|
|||||||
return 'unsupported'
|
return 'unsupported'
|
||||||
}
|
}
|
||||||
const isVideo = (m: TrainingMaterial) => previewKind(m) === 'video' || (!m.knowledge_id && !!m.file_key)
|
const isVideo = (m: TrainingMaterial) => previewKind(m) === 'video' || (!m.knowledge_id && !!m.file_key)
|
||||||
const isDoc = (m: TrainingMaterial) => !isVideo(m) && (m.knowledge_id || m.file_key)
|
|
||||||
|
|
||||||
const kindIcon = (m: TrainingMaterial) => {
|
const kindIcon = (m: TrainingMaterial) => {
|
||||||
const kind = previewKind(m)
|
const kind = previewKind(m)
|
||||||
@@ -225,28 +216,27 @@ const stopHeartbeat = () => {
|
|||||||
docPercentStep = 0
|
docPercentStep = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// 打开课件:文档带 knowledge_id 时走知识库流(DocumentPreview 自带拉取);
|
// 打开课件:统一走培训域课件文件流(blob 播放/渲染)。不走知识库文档预览
|
||||||
// 视频/仅 file_key 的课件统一走课件文件流(blob 播放/渲染)。
|
// 通道(/knowledge/:id/preview):该通道按调用方所在空间做知识库鉴权,000160
|
||||||
|
// 跨空间学员(培训数据在档案空间)会被 403「Permission denied」拦截;培训域
|
||||||
|
// 文件流按解析后的培训租户服务端取文件,与下载/和信课程抽屉同口径。
|
||||||
const openMaterial = async (m: TrainingMaterial) => {
|
const openMaterial = async (m: TrainingMaterial) => {
|
||||||
if (current.value?.id === m.id) return
|
if (current.value?.id === m.id) return
|
||||||
stopHeartbeat()
|
stopHeartbeat()
|
||||||
current.value = m
|
current.value = m
|
||||||
docBlob.value = null
|
docBlob.value = null
|
||||||
if (!m.knowledge_id && !m.file_key) return
|
if (!m.knowledge_id && !m.file_key) return
|
||||||
if (isVideo(m) || !m.knowledge_id) {
|
previewLoading.value = true
|
||||||
previewLoading.value = true
|
try {
|
||||||
try {
|
docBlob.value = await downloadMaterialFile(m.id)
|
||||||
docBlob.value = await downloadMaterialFile(m.id)
|
if (isVideo(m)) bindVideoHeartbeat()
|
||||||
if (isVideo(m)) bindVideoHeartbeat()
|
else startDocHeartbeat(m)
|
||||||
} catch {
|
} catch {
|
||||||
MessagePlugin.error('课件文件加载失败,请稍后重试')
|
MessagePlugin.error('课件文件加载失败,请稍后重试')
|
||||||
current.value = null
|
current.value = null
|
||||||
} finally {
|
} finally {
|
||||||
previewLoading.value = false
|
previewLoading.value = false
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
startDocHeartbeat(m)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- 学习进度心跳 ----
|
// ---- 学习进度心跳 ----
|
||||||
|
|||||||
@@ -60,11 +60,6 @@
|
|||||||
<t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" />
|
<t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" />
|
||||||
</template>
|
</template>
|
||||||
<StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" />
|
<StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" />
|
||||||
<template v-else-if="activeTab === 'members'">
|
|
||||||
<!-- 职称角色对经理开放(000159):与配置中心「角色权限」页签同口径 -->
|
|
||||||
<MemberPanel v-if="canManageConfig" />
|
|
||||||
<t-empty v-else class="training-empty" description="职称角色维护仅人事/经理可见" />
|
|
||||||
</template>
|
|
||||||
<template v-else-if="activeTab === 'rules'">
|
<template v-else-if="activeTab === 'rules'">
|
||||||
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
|
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
|
||||||
<RulePanel v-if="canManageConfig" />
|
<RulePanel v-if="canManageConfig" />
|
||||||
@@ -86,7 +81,6 @@ import PlanPanel from './components/PlanPanel.vue'
|
|||||||
import CoursePanel from './components/CoursePanel.vue'
|
import CoursePanel from './components/CoursePanel.vue'
|
||||||
import LibraryPanel from './components/LibraryPanel.vue'
|
import LibraryPanel from './components/LibraryPanel.vue'
|
||||||
import SignPanel from './components/SignPanel.vue'
|
import SignPanel from './components/SignPanel.vue'
|
||||||
import MemberPanel from './components/MemberPanel.vue'
|
|
||||||
import StudyPanel from './components/StudyPanel.vue'
|
import StudyPanel from './components/StudyPanel.vue'
|
||||||
import RulePanel from './components/RulePanel.vue'
|
import RulePanel from './components/RulePanel.vue'
|
||||||
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
|
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
|
||||||
@@ -102,7 +96,7 @@ const TRAINING_TABS_META: Record<string, { title: string; desc: string }> = {
|
|||||||
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
|
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
|
||||||
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
|
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
|
||||||
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
|
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
|
||||||
members: { title: '职称角色', desc: '名册来自「组织架构」,此处维护员工职称角色' },
|
// members(职称角色)已并入「组织架构」页维护,路由 /platform/training/members 重定向过去
|
||||||
rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' },
|
rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' },
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,10 +110,12 @@ const authStore = useAuthStore()
|
|||||||
// 职称角色字典(配置中心可配);myRoles = 实际分配角色按「权限分配」传递展开后的
|
// 职称角色字典(配置中心可配);myRoles = 实际分配角色按「权限分配」传递展开后的
|
||||||
// 权限并集 —— 各子页既有 canXxx 判断因此对自定义角色自动生效,无需逐一修改。
|
// 权限并集 —— 各子页既有 canXxx 判断因此对自定义角色自动生效,无需逐一修改。
|
||||||
const roleDict = ref<TrainingRoleDef[]>([])
|
const roleDict = ref<TrainingRoleDef[]>([])
|
||||||
|
const loadRoleDict = () =>
|
||||||
|
fetchRoleDict().then((d) => {
|
||||||
|
roleDict.value = d
|
||||||
|
})
|
||||||
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
|
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
|
||||||
fetchRoleDict().then((d) => {
|
loadRoleDict()
|
||||||
roleDict.value = d
|
|
||||||
})
|
|
||||||
|
|
||||||
// 空间 Admin/Owner 视同培训管理角色(与后端 requireRoles 的 bypass 一致),
|
// 空间 Admin/Owner 视同培训管理角色(与后端 requireRoles 的 bypass 一致),
|
||||||
// 保证冷启动时管理员即可进入职称角色/配置中心子页完成首批授权。
|
// 保证冷启动时管理员即可进入职称角色/配置中心子页完成首批授权。
|
||||||
@@ -213,6 +209,15 @@ const loadProfile = async () => {
|
|||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
loadProfile()
|
loadProfile()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 侧栏在企业培训各子页间切换时复用同一页面实例(不重挂载):本人职称角色可能刚在
|
||||||
|
// 「职称角色」子页被分配/回收,角色权限字典可能刚在「配置中心」子页被修改。切换
|
||||||
|
// 子页时重取这两项,否则各子页会沿用挂载时的旧 myRoles —— 例如刚给自己分配了
|
||||||
|
// 课长,课程管理的核验/删除按钮却不出现,须整页刷新才生效。
|
||||||
|
watch(activeTab, () => {
|
||||||
|
loadProfile()
|
||||||
|
loadRoleDict()
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="less" scoped>
|
<style lang="less" scoped>
|
||||||
|
|||||||
@@ -98,13 +98,57 @@
|
|||||||
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
:description="filter === 'mine' ? '暂无与我相关的课程' : '暂无已发布课程(课程管理发布后在此展示)'"
|
||||||
/>
|
/>
|
||||||
</t-loading>
|
</t-loading>
|
||||||
|
|
||||||
|
<!-- 课程学习抽屉(000160):和信课程卡片点开即学 —— 课件在线预览 + 下载 -->
|
||||||
|
<t-drawer
|
||||||
|
v-model:visible="learningVisible"
|
||||||
|
:header="learningCourse?.name || '课程学习'"
|
||||||
|
size="860px"
|
||||||
|
:footer="false"
|
||||||
|
>
|
||||||
|
<div v-if="learningCourse" class="course-learning">
|
||||||
|
<p class="course-learning__meta">
|
||||||
|
{{
|
||||||
|
[
|
||||||
|
learningCourse.owner_dept_name,
|
||||||
|
learningCourse.suitable_members,
|
||||||
|
learningCourse.lecturer_name,
|
||||||
|
learningCourse.hours ? `${learningCourse.hours} 学时` : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' · ')
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
<t-loading :loading="learningLoading" text="课件加载中...">
|
||||||
|
<DocumentPreview
|
||||||
|
v-if="learningBlob"
|
||||||
|
:source-blob="learningBlob"
|
||||||
|
:file-type="learningFileType"
|
||||||
|
:file-name="learningCourse.file_name || learningCourse.name"
|
||||||
|
:active="learningVisible"
|
||||||
|
fill-height
|
||||||
|
/>
|
||||||
|
<t-empty
|
||||||
|
v-else-if="!learningLoading"
|
||||||
|
class="catalog-empty"
|
||||||
|
:description="learningCourse.file_name ? '课件加载失败,可下载后本地查看' : '该课程未上传课件,请联系讲师或人事补充'"
|
||||||
|
/>
|
||||||
|
</t-loading>
|
||||||
|
<div v-if="learningCourse.file_name" class="course-learning__actions">
|
||||||
|
<t-button variant="outline" theme="primary" @click="onDownloadLearningMaterial">下载课件</t-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</t-drawer>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
|
import { MessagePlugin } from 'tdesign-vue-next'
|
||||||
|
import DocumentPreview from '@/components/document-preview.vue'
|
||||||
import {
|
import {
|
||||||
|
downloadCourseLibraryMaterial,
|
||||||
getMyProfile,
|
getMyProfile,
|
||||||
listCourses,
|
listCourses,
|
||||||
listCourseLibrary,
|
listCourseLibrary,
|
||||||
@@ -125,9 +169,13 @@ const props = defineProps<{ roles: string[]; admin?: boolean }>()
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
|
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
|
||||||
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护;
|
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护;
|
||||||
// 和信课程卡片为课程资产展示(000154),无学习页不跳转。
|
// 和信课程卡片点开即学(000160):打开课件在线预览抽屉。
|
||||||
const openCourse = (card: CatalogCard) => {
|
const openCourse = (card: CatalogCard) => {
|
||||||
if (card.kind === 'library') return
|
if (card.kind === 'library') {
|
||||||
|
const course = hexinCourses.value.find((c) => c.id === card.id)
|
||||||
|
if (course) openLibraryCourse(course)
|
||||||
|
return
|
||||||
|
}
|
||||||
if (card.unpublished) {
|
if (card.unpublished) {
|
||||||
goMaintain(card.id)
|
goMaintain(card.id)
|
||||||
return
|
return
|
||||||
@@ -140,6 +188,52 @@ const goMaintain = (courseId: string) => {
|
|||||||
router.push({ path: '/platform/training/course', query: { courseId } })
|
router.push({ path: '/platform/training/course', query: { courseId } })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 和信课程学习抽屉(000160):点开卡片 → 课件在线预览 + 下载 ----
|
||||||
|
const learningVisible = ref(false)
|
||||||
|
const learningCourse = ref<TrainingLibraryCourse | null>(null)
|
||||||
|
const learningBlob = ref<Blob | null>(null)
|
||||||
|
const learningLoading = ref(false)
|
||||||
|
// 预览组件按扩展名分派渲染器(pptx/pdf/docx/图片/文本...)
|
||||||
|
const learningFileType = computed(() => {
|
||||||
|
const name = learningCourse.value?.file_name || ''
|
||||||
|
const dot = name.lastIndexOf('.')
|
||||||
|
return dot >= 0 ? name.slice(dot + 1).toLowerCase() : ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const openLibraryCourse = (course: TrainingLibraryCourse) => {
|
||||||
|
learningCourse.value = course
|
||||||
|
learningBlob.value = null
|
||||||
|
learningVisible.value = true
|
||||||
|
if (!course.file_name) return
|
||||||
|
learningLoading.value = true
|
||||||
|
downloadCourseLibraryMaterial(course.id)
|
||||||
|
.then((blob) => {
|
||||||
|
learningBlob.value = blob
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
learningBlob.value = null
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
learningLoading.value = false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const onDownloadLearningMaterial = async () => {
|
||||||
|
const course = learningCourse.value
|
||||||
|
if (!course?.file_name) return
|
||||||
|
try {
|
||||||
|
const blob = await downloadCourseLibraryMaterial(course.id)
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = url
|
||||||
|
a.download = course.file_name || `${course.name}课件`
|
||||||
|
a.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error('课件下载失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const courses = ref<TrainingCourse[]>([])
|
const courses = ref<TrainingCourse[]>([])
|
||||||
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计
|
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的培训」与待维护统计
|
||||||
@@ -164,13 +258,24 @@ const keyword = ref('')
|
|||||||
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
|
||||||
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
|
||||||
|
|
||||||
// 「和信课程」(000154):课程管理中已发布、且部门范围覆盖查看人的课程
|
// 「和信课程」(000160):已发布 + 适合人员覆盖查看人 —— 「全部」全员可见;
|
||||||
// (所属部门为空 = 全员课程;有部门则需与我的部门一致)
|
// 000159 多部门口径:值按「、」拆分(逗号/分号兼容归一)后与查看人部门名做
|
||||||
|
// 成员匹配;未设置适合人员的存量课程沿用原部门范围口径(所属部门为空 = 全员,
|
||||||
|
// 否则须与我的部门一致)。后端 scope=catalog 已按同口径过滤,此处保留客户端兜底。
|
||||||
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
const myDeptId = computed(() => myProfile.value?.dept_id || '')
|
||||||
|
const myDeptName = computed(() => (myProfile.value?.dept_name || '').trim())
|
||||||
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
const hexinCourses = computed<TrainingLibraryCourse[]>(() =>
|
||||||
libraryItems.value.filter(
|
libraryItems.value.filter((c) => {
|
||||||
(c) => c.publish_status === 'published' && (!c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value),
|
if (c.publish_status !== 'published') return false
|
||||||
),
|
const suitableNames = (c.suitable_members || '')
|
||||||
|
.split(/[、,,;;]/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
if (suitableNames.length) {
|
||||||
|
return suitableNames.includes('全部') || (!!myDeptName.value && suitableNames.includes(myDeptName.value))
|
||||||
|
}
|
||||||
|
return !c.owner_dept_id || !myDeptId.value || c.owner_dept_id === myDeptId.value
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const statsText = computed(() => {
|
const statsText = computed(() => {
|
||||||
@@ -448,8 +553,9 @@ const loadAll = async () => {
|
|||||||
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
|
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
|
||||||
getMyProfile().catch(() => null),
|
getMyProfile().catch(() => null),
|
||||||
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
|
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
|
||||||
// 和信课程目录(000154):课程管理已发布课程
|
// 和信课程目录(000160):scope=catalog —— 已发布 + 适合人员覆盖查看人
|
||||||
listCourseLibrary({ page_size: 500 }).catch(() => null),
|
// (全部/本部门;未设置沿用部门范围口径),不按维护角色收窄,全体员工同源
|
||||||
|
listCourseLibrary({ page_size: 500, scope: 'catalog' }).catch(() => null),
|
||||||
// 我的考试记录(000154)
|
// 我的考试记录(000154)
|
||||||
listMyExamRecords().catch(() => null),
|
listMyExamRecords().catch(() => null),
|
||||||
])
|
])
|
||||||
@@ -573,6 +679,26 @@ onMounted(loadAll)
|
|||||||
padding: 48px 0;
|
padding: 48px 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 课程学习抽屉(000160):元信息行 + 预览主体 + 下载操作
|
||||||
|
.course-learning {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
min-height: 100%;
|
||||||
|
|
||||||
|
&__meta {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 「我的考试」成绩列:及格绿/不及格红
|
// 「我的考试」成绩列:及格绿/不及格红
|
||||||
.exam-score {
|
.exam-score {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
@@ -71,7 +71,7 @@
|
|||||||
variant="text" theme="primary" size="small" :disabled="saving"
|
variant="text" theme="primary" size="small" :disabled="saving"
|
||||||
@click="onPublish(row)"
|
@click="onPublish(row)"
|
||||||
>发布</t-button>
|
>发布</t-button>
|
||||||
<t-button variant="text" size="small" @click="openDetail(row)">详情</t-button>
|
<t-button variant="text" size="small" @click="openDetail(row)">调整</t-button>
|
||||||
<t-button variant="text" size="small" @click="openChangeLogs(row)">记录</t-button>
|
<t-button variant="text" size="small" @click="openChangeLogs(row)">记录</t-button>
|
||||||
<t-button v-if="canManage" variant="text" theme="danger" size="small" @click="onDelete(row)">删除</t-button>
|
<t-button v-if="canManage" variant="text" theme="danger" size="small" @click="onDelete(row)">删除</t-button>
|
||||||
</template>
|
</template>
|
||||||
@@ -195,16 +195,16 @@
|
|||||||
</template>
|
</template>
|
||||||
</t-dialog>
|
</t-dialog>
|
||||||
|
|
||||||
<!-- 计划详情:计划编号展示 + 课程名称(课程管理选择,信息锁定) + 六项授课安排维护 -->
|
<!-- 计划调整:计划编号展示 + 课程名称/讲师(000161 可调整,讲师改动回写课程管理并重置待核验) + 六项授课安排维护 -->
|
||||||
<t-dialog v-model:visible="sessionsVisible" :header="`计划详情 · ${activeCourse?.name || ''}`" width="760" :footer="false">
|
<t-dialog v-model:visible="sessionsVisible" :header="`计划调整 · ${activeCourse?.name || ''}`" width="760" :footer="false">
|
||||||
<t-form label-width="90" class="detail-form">
|
<t-form label-width="90" class="detail-form">
|
||||||
<t-form-item label="计划编号">
|
<t-form-item label="计划编号">
|
||||||
<t-input :value="activeCourse?.plan_code || '-'" disabled />
|
<t-input :value="activeCourse?.plan_code || '-'" disabled />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="课程名称">
|
<t-form-item label="课程名称">
|
||||||
<!-- 未关联课程管理的计划可选定课程(选定后信息锁定);已关联直接锁定展示 -->
|
<!-- 000161 可切换关联课程:改选即换 library_course_id,类型/形式随新课程带出;
|
||||||
|
讲师改动保存后回写课程管理并重置待核验,发布前须重新签核 -->
|
||||||
<t-select
|
<t-select
|
||||||
v-if="!activeCourse?.library_course_id"
|
|
||||||
v-model="editForm.library_course_id"
|
v-model="editForm.library_course_id"
|
||||||
:disabled="!canManage"
|
:disabled="!canManage"
|
||||||
clearable
|
clearable
|
||||||
@@ -215,13 +215,23 @@
|
|||||||
>
|
>
|
||||||
<t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" />
|
<t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" />
|
||||||
</t-select>
|
</t-select>
|
||||||
<t-input v-else :value="editForm.name" disabled />
|
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="类型">
|
<t-form-item label="类型">
|
||||||
<t-input :value="formTypeDisplay" disabled />
|
<t-input :value="formTypeDisplay" disabled />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="讲师">
|
<t-form-item label="讲师">
|
||||||
<t-input :value="lecturerDisplay(editForm.lecturer_id)" disabled placeholder="随课程带出" />
|
<!-- 000161 计划侧可改讲师:名册选择或直接输入外部讲师姓名 -->
|
||||||
|
<t-select
|
||||||
|
v-model="editForm.lecturer_id"
|
||||||
|
:disabled="!canManage"
|
||||||
|
clearable
|
||||||
|
filterable
|
||||||
|
creatable
|
||||||
|
placeholder="从讲师名册选择或直接输入外部讲师姓名"
|
||||||
|
style="width: 100%"
|
||||||
|
>
|
||||||
|
<t-option v-for="l in lecturers" :key="l.id" :label="l.name" :value="l.id" />
|
||||||
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="所属部门">
|
<t-form-item label="所属部门">
|
||||||
<t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" />
|
<t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" />
|
||||||
@@ -1159,19 +1169,40 @@ const onSave = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const onPublish = async (row: TrainingCourse) => {
|
const onPublish = async (row: TrainingCourse) => {
|
||||||
// 与后端同口径的前置校验:线上必须有课件,线下必须有讲师
|
// 与后端同口径的前置校验(000161):线上必须有课件;线下须有讲师(外部姓名
|
||||||
|
// 亦可)/授课时间/授课地点;两者均须已设置参加人员且关联课程已签核
|
||||||
if (row.mode === 'online') {
|
if (row.mode === 'online') {
|
||||||
try {
|
try {
|
||||||
const res = await listMaterials(row.id)
|
const res = await listMaterials(row.id)
|
||||||
if (!(unwrap(res) || []).length) {
|
if (!(unwrap(res) || []).length) {
|
||||||
MessagePlugin.warning(`「${row.name}」是线上计划,发布前需先登记课件资料`)
|
// 计划未自带课件时回退课程管理课件(名称登记/文件/知识库文档,
|
||||||
return
|
// 000156 随所选课程带出,详情弹窗「更换」也回写主数据)与后端同口径
|
||||||
|
const lc = libraryCourses.value.find((c) => c.id === (row.library_course_id || ''))
|
||||||
|
const hasLibCourseware = !!(lc?.material_name || lc?.file_name || lc?.knowledge_id)
|
||||||
|
if (!hasLibCourseware) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线上计划,发布前需先登记课件资料`)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* 查询失败时交由后端校验兜底 */
|
/* 查询失败时交由后端校验兜底 */
|
||||||
}
|
}
|
||||||
} else if (!row.lecturer_id) {
|
} else {
|
||||||
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「详情」中指定讲师`)
|
if (!row.lecturer_id && !row.lecturer_external) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中指定讲师`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!row.teach_time) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课时间`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!row.location) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课地点`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row.post_scope) {
|
||||||
|
MessagePlugin.warning(`「${row.name}」发布前需先在「调整」中设置参加人员`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -1339,42 +1370,55 @@ const ensureCourseSession = async (
|
|||||||
// 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。
|
// 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。
|
||||||
// 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须
|
// 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须
|
||||||
// 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。
|
// 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。
|
||||||
const detailSavePayload = (row: TrainingCourse) => ({
|
// 000161 讲师解析:名册 id 直接用;非名册值(creatable 直接输入)按外部讲师姓名落库
|
||||||
id: row.id,
|
const resolveDetailLecturer = (row: TrainingCourse) => {
|
||||||
code: row.code,
|
const v = (editForm.value.lecturer_id || '').trim()
|
||||||
name: editForm.value.name,
|
if (!v) return { lecturerId: '', external: row.lecturer_external || '' }
|
||||||
mode: editForm.value.mode,
|
if (lecturers.value.some((l) => l.id === v)) return { lecturerId: v, external: '' }
|
||||||
type: editForm.value.type,
|
return { lecturerId: '', external: v }
|
||||||
hours: editForm.value.hours,
|
}
|
||||||
credits: editForm.value.credits,
|
|
||||||
exam_enabled: row.exam_enabled,
|
const detailSavePayload = (row: TrainingCourse) => {
|
||||||
dept_ids: editForm.value.dept_ids,
|
const lecturer = resolveDetailLecturer(row)
|
||||||
lecturer_id: editForm.value.lecturer_id || undefined,
|
return ({
|
||||||
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
|
id: row.id,
|
||||||
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
|
code: row.code,
|
||||||
description: row.description,
|
name: editForm.value.name,
|
||||||
material_ids: row.material_ids,
|
mode: editForm.value.mode,
|
||||||
tags: row.tags,
|
type: editForm.value.type,
|
||||||
status: row.status,
|
hours: editForm.value.hours,
|
||||||
teach_time: teachTimeOf(editForm.value),
|
credits: editForm.value.credits,
|
||||||
planned_time: row.planned_time || '',
|
exam_enabled: row.exam_enabled,
|
||||||
// 其余需求确认同步字段原样透传(详情表单不编辑,防止保存时被零值覆盖丢失)
|
dept_ids: editForm.value.dept_ids,
|
||||||
train_type: row.train_type || '',
|
lecturer_id: lecturer.lecturerId || undefined,
|
||||||
plant: row.plant || '',
|
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
|
||||||
location: row.location || '',
|
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
|
||||||
session_count: row.session_count || 0,
|
description: row.description,
|
||||||
lecturer_external: row.lecturer_external || '',
|
material_ids: row.material_ids,
|
||||||
remark: row.remark || '',
|
tags: row.tags,
|
||||||
// 课程管理关联(未关联的存量计划可在此选定课程;关联后服务端锁定带出字段)
|
status: row.status,
|
||||||
library_course_id: editForm.value.library_course_id || row.library_course_id || '',
|
teach_time: teachTimeOf(editForm.value),
|
||||||
})
|
planned_time: row.planned_time || '',
|
||||||
|
// 其余需求确认同步字段原样透传(详情表单不编辑,防止保存时被零值覆盖丢失)
|
||||||
|
train_type: row.train_type || '',
|
||||||
|
plant: row.plant || '',
|
||||||
|
location: row.location || '',
|
||||||
|
session_count: row.session_count || 0,
|
||||||
|
// 000161 讲师计划侧可改:名册 id 或外部讲师姓名
|
||||||
|
lecturer_external: lecturer.external,
|
||||||
|
remark: row.remark || '',
|
||||||
|
// 课程管理关联(000161 可切换;切换后类型/形式随新课程带出)
|
||||||
|
library_course_id: editForm.value.library_course_id || row.library_course_id || '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const onSaveDetail = async () => {
|
const onSaveDetail = async () => {
|
||||||
const row = activeCourse.value
|
const row = activeCourse.value
|
||||||
if (!row) return
|
if (!row) return
|
||||||
// 讲师随课程管理锁定:缺失时提示去课程管理维护(发布时后端也会强制校验)
|
// 线下计划须指定讲师(名册 id 或外部姓名;发布时后端也会强制校验)
|
||||||
if (row.mode === 'offline' && !editForm.value.lecturer_id) {
|
const lecturer = resolveDetailLecturer(row)
|
||||||
MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师')
|
if (editForm.value.mode === 'offline' && !lecturer.lecturerId && !lecturer.external) {
|
||||||
|
MessagePlugin.warning('线下计划需先指定讲师(从名册选择或输入外部讲师姓名)')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
detailSaving.value = true
|
detailSaving.value = true
|
||||||
@@ -1388,7 +1432,7 @@ const onSaveDetail = async () => {
|
|||||||
await saveCourse(detailSavePayload(row))
|
await saveCourse(detailSavePayload(row))
|
||||||
const sessionOpts = {
|
const sessionOpts = {
|
||||||
mode: editForm.value.mode,
|
mode: editForm.value.mode,
|
||||||
lecturerId: editForm.value.lecturer_id || undefined,
|
lecturerId: lecturer.lecturerId || undefined,
|
||||||
startAt: editForm.value.start_at,
|
startAt: editForm.value.start_at,
|
||||||
location: editForm.value.location,
|
location: editForm.value.location,
|
||||||
hours: editForm.value.hours,
|
hours: editForm.value.hours,
|
||||||
@@ -1402,7 +1446,7 @@ const onSaveDetail = async () => {
|
|||||||
end_at: editForm.value.start_at ? new Date(new Date(editForm.value.start_at).getTime() + editForm.value.hours * 3600 * 1000).toISOString() : '',
|
end_at: editForm.value.start_at ? new Date(new Date(editForm.value.start_at).getTime() + editForm.value.hours * 3600 * 1000).toISOString() : '',
|
||||||
location: editForm.value.location,
|
location: editForm.value.location,
|
||||||
capacity: existing?.capacity ?? 0,
|
capacity: existing?.capacity ?? 0,
|
||||||
lecturer_id: editForm.value.lecturer_id || undefined,
|
lecturer_id: lecturer.lecturerId || undefined,
|
||||||
// [2026-11 推学员] 编辑排课时同步通知方式
|
// [2026-11 推学员] 编辑排课时同步通知方式
|
||||||
notify_mode: editForm.value.notify_mode,
|
notify_mode: editForm.value.notify_mode,
|
||||||
})
|
})
|
||||||
@@ -1426,8 +1470,8 @@ const onSaveDetail = async () => {
|
|||||||
)
|
)
|
||||||
sessionsVisible.value = false
|
sessionsVisible.value = false
|
||||||
loadAll()
|
loadAll()
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
MessagePlugin.error('保存失败,请稍后重试')
|
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
|
||||||
} finally {
|
} finally {
|
||||||
detailSaving.value = false
|
detailSaving.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -142,8 +142,12 @@
|
|||||||
<t-input v-model="form.name" placeholder="请输入课程名称" />
|
<t-input v-model="form.name" placeholder="请输入课程名称" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="所属部门">
|
<t-form-item label="所属部门">
|
||||||
<!-- 对应需求表「主办单位」:从组织架构部门选择(批量导入按部门名匹配) -->
|
<!-- 对应需求表「主办单位」:锁定为创建人(当前登录人)所属部门,不可修改
|
||||||
<t-select v-model="form.owner_dept_id" clearable filterable placeholder="从组织架构选择所属部门(选填)" style="width: 100%">
|
(000160,服务端同口径强制;无部门档案时可手动选择) -->
|
||||||
|
<t-select
|
||||||
|
v-model="form.owner_dept_id" :disabled="Boolean(myDeptId)" :clearable="!myDeptId"
|
||||||
|
filterable :placeholder="myDeptId ? '创建人所属部门(不可修改)' : '从组织架构选择所属部门(选填)'" style="width: 100%"
|
||||||
|
>
|
||||||
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
|
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
|
||||||
</t-select>
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
@@ -151,8 +155,14 @@
|
|||||||
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
|
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="适合人员">
|
<t-form-item label="适合人员">
|
||||||
<!-- 对应需求表「参加人员」:自由文本,如:财会人员 -->
|
<!-- 000159 部门多选口径:归属部门(可多选)或「全部」(互斥);发布后
|
||||||
<t-input v-model="form.suitable_members" placeholder="适合参加的人员(选填),如:财会人员" />
|
培训中心按此展示给对应人员,存量自由文本值回显为选项 -->
|
||||||
|
<t-select
|
||||||
|
v-model="suitableList" clearable filterable multiple
|
||||||
|
placeholder="选择部门(可多选),或选「全部」" style="width: 100%"
|
||||||
|
>
|
||||||
|
<t-option v-for="opt in suitableOptions" :key="opt" :value="opt" :label="opt" />
|
||||||
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="分类">
|
<t-form-item label="分类">
|
||||||
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
|
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
|
||||||
@@ -468,7 +478,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
import { MessagePlugin } from 'tdesign-vue-next'
|
import { MessagePlugin } from 'tdesign-vue-next'
|
||||||
import * as XLSX from 'xlsx'
|
import * as XLSX from 'xlsx'
|
||||||
import { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
import { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
||||||
@@ -525,6 +535,34 @@ const configCategories = ref<string[]>([])
|
|||||||
const myDeptId = ref('')
|
const myDeptId = ref('')
|
||||||
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
|
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
|
||||||
const myUserId = ref('')
|
const myUserId = ref('')
|
||||||
|
// 本人部门名(000160):「适合人员」默认值 = 创建人所属部门名;经 me 的
|
||||||
|
// dept_name 联查字段直取,回退本地部门名册映射。
|
||||||
|
const myDeptName = computed(() => {
|
||||||
|
const fromMe = (meDeptName.value || '').trim()
|
||||||
|
if (fromMe) return fromMe
|
||||||
|
const hit = depts.value.find((d) => d.id === myDeptId.value)
|
||||||
|
return hit?.name || ''
|
||||||
|
})
|
||||||
|
// /training/members/me 联查返回的部门名(handler 000160 起填充)
|
||||||
|
const meDeptName = ref('')
|
||||||
|
// 「适合人员」下拉选项(000160/000159 多选口径):全部 + 各部门名;存量自由文本值保留可选
|
||||||
|
const suitableOptions = computed(() => {
|
||||||
|
const opts = ['全部', ...depts.value.map((d) => d.name)]
|
||||||
|
for (const v of splitSuitable(form.value.suitable_members)) {
|
||||||
|
if (!opts.includes(v)) opts.push(v)
|
||||||
|
}
|
||||||
|
return opts
|
||||||
|
})
|
||||||
|
// 适合人员多选值(000159):form.suitable_members 存「、」join 后的落库串,
|
||||||
|
// 选项交互走本数组;「全部」与具体部门互斥(勾全部清部门,勾部门移除全部)。
|
||||||
|
const suitableList = ref<string[]>([])
|
||||||
|
const splitSuitable = (v: string) =>
|
||||||
|
(v || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
|
||||||
|
watch(suitableList, (list, prev) => {
|
||||||
|
if (list.includes('全部') && list.length > 1) {
|
||||||
|
suitableList.value = (prev || []).includes('全部') ? list.filter((v) => v !== '全部') : ['全部']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// 核验/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
|
// 核验/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
|
||||||
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
|
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
|
||||||
@@ -618,6 +656,7 @@ const loadAll = async () => {
|
|||||||
const meBody = me && unwrap(me)
|
const meBody = me && unwrap(me)
|
||||||
myDeptId.value = meBody?.dept_id || ''
|
myDeptId.value = meBody?.dept_id || ''
|
||||||
myUserId.value = meBody?.user_id || ''
|
myUserId.value = meBody?.user_id || ''
|
||||||
|
meDeptName.value = meBody?.dept_name || ''
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
loading.value = false
|
||||||
}
|
}
|
||||||
@@ -739,10 +778,11 @@ const openForm = (row?: TrainingLibraryCourse) => {
|
|||||||
id: row?.id || '',
|
id: row?.id || '',
|
||||||
code: row?.code || '',
|
code: row?.code || '',
|
||||||
name: row?.name || '',
|
name: row?.name || '',
|
||||||
// 新增默认当前登录用户所在部门;编辑保持原部门
|
// 新增默认当前登录用户所在部门(锁定不可改);编辑保持原部门
|
||||||
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
||||||
description: row?.description || '',
|
description: row?.description || '',
|
||||||
suitable_members: row?.suitable_members || '',
|
// 适合人员(000160):新增默认创建人所属部门名,可改「全部」或其他部门
|
||||||
|
suitable_members: row?.suitable_members || (row ? '' : myDeptName.value),
|
||||||
category: row?.category || '',
|
category: row?.category || '',
|
||||||
type: row?.type === 'elective' ? 'elective' : 'required',
|
type: row?.type === 'elective' ? 'elective' : 'required',
|
||||||
mode: row?.mode === 'online' ? 'online' : 'offline',
|
mode: row?.mode === 'online' ? 'online' : 'offline',
|
||||||
@@ -752,6 +792,8 @@ const openForm = (row?: TrainingLibraryCourse) => {
|
|||||||
file_name: row?.file_name || '',
|
file_name: row?.file_name || '',
|
||||||
clear_file: false,
|
clear_file: false,
|
||||||
}
|
}
|
||||||
|
// 适合人员多选回显(000159):落库串「、」join → 数组;新增默认本部门
|
||||||
|
suitableList.value = splitSuitable(form.value.suitable_members)
|
||||||
formVisible.value = true
|
formVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -771,6 +813,8 @@ const onSave = async () => {
|
|||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const lecturer = resolveLecturer(form.value.lecturer.trim())
|
const lecturer = resolveLecturer(form.value.lecturer.trim())
|
||||||
|
// 适合人员多选 → 「、」join 落库(000159);「全部」与部门互斥由 watch 保证
|
||||||
|
form.value.suitable_members = suitableList.value.join('、')
|
||||||
const res = await saveCourseLibraryItem({
|
const res = await saveCourseLibraryItem({
|
||||||
id: form.value.id || undefined,
|
id: form.value.id || undefined,
|
||||||
name: form.value.name.trim(),
|
name: form.value.name.trim(),
|
||||||
|
|||||||
@@ -1,323 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="member-panel">
|
|
||||||
<!-- 员工档案(名册来自组织架构)+ 职称角色 -->
|
|
||||||
<div class="panel-box member-layout__members">
|
|
||||||
<div class="panel-box__header">
|
|
||||||
<span class="panel-box__title">员工档案</span>
|
|
||||||
<div class="member-panel__hint">
|
|
||||||
员工与部门在「<a class="member-panel__link" @click="goOrgCenter">组织架构</a>」中统一维护,此处仅配置职称角色
|
|
||||||
<t-button variant="outline" theme="primary" size="small" :loading="syncing" class="oa-sync-btn" @click="onPreviewSync">
|
|
||||||
从OA同步企微账号
|
|
||||||
</t-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<t-table :data="members" :columns="memberColumns" row-key="id" size="small" :loading="loading">
|
|
||||||
<template #user_name="{ row }">
|
|
||||||
<t-tooltip :content="memberName(row)" :disabled="!memberName(row)">
|
|
||||||
<span class="member-name">{{ memberName(row) || '-' }}</span>
|
|
||||||
</t-tooltip>
|
|
||||||
</template>
|
|
||||||
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
|
||||||
<template #wecom_userid="{ row }">
|
|
||||||
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
|
|
||||||
</template>
|
|
||||||
<template #roles="{ row }">
|
|
||||||
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
|
|
||||||
</template>
|
|
||||||
<template #op="{ row }">
|
|
||||||
<t-button variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
|
|
||||||
<t-button variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
|
|
||||||
</template>
|
|
||||||
</t-table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
|
|
||||||
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
|
|
||||||
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
|
|
||||||
<template #footer>
|
|
||||||
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
|
|
||||||
</template>
|
|
||||||
</t-dialog>
|
|
||||||
|
|
||||||
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
|
|
||||||
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
|
|
||||||
<template v-if="syncSummary">
|
|
||||||
<div class="sync-stats">
|
|
||||||
<span>本地员工 {{ syncSummary.local_candidates }}</span>
|
|
||||||
<span>OA 命中 {{ syncSummary.local_matched }}</span>
|
|
||||||
<span>已一致 {{ syncSummary.already_bound }}</span>
|
|
||||||
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
|
|
||||||
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
|
|
||||||
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
|
|
||||||
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
|
|
||||||
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
|
|
||||||
{{ cf.employee_no }} {{ cf.user_name || '' }}:
|
|
||||||
{{ conflictText(cf) }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="syncSummary.would_update" class="sync-section">
|
|
||||||
<div class="sync-section__title">将写入(最多展示 20 条)</div>
|
|
||||||
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
|
|
||||||
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
|
|
||||||
无需更新:绑定已一致或 OA 无匹配数据。
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="sync-footer">
|
|
||||||
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
|
|
||||||
theme="primary" :loading="syncing" @click="onApplySync">
|
|
||||||
确认写入
|
|
||||||
</t-button>
|
|
||||||
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</t-dialog>
|
|
||||||
|
|
||||||
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
|
|
||||||
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
|
|
||||||
<t-select v-model="roleSelection" multiple style="width: 100%">
|
|
||||||
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
|
|
||||||
</t-select>
|
|
||||||
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
|
|
||||||
<template #footer>
|
|
||||||
<t-button theme="primary" :loading="saving" @click="onSaveRoles">保存</t-button>
|
|
||||||
</template>
|
|
||||||
</t-dialog>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import { computed, onMounted, ref } from 'vue'
|
|
||||||
import { useRouter } from 'vue-router'
|
|
||||||
import { MessagePlugin } from 'tdesign-vue-next'
|
|
||||||
import {
|
|
||||||
fetchRoleDict,
|
|
||||||
listMembers,
|
|
||||||
listPlatformUsers,
|
|
||||||
roleLabelOf,
|
|
||||||
updateMemberRoles,
|
|
||||||
updateMemberWecomUserid,
|
|
||||||
applyWecomUseridSync,
|
|
||||||
previewWecomUseridSync,
|
|
||||||
type PlatformUser,
|
|
||||||
type TrainingMember,
|
|
||||||
type TrainingRoleDef,
|
|
||||||
type WecomSyncConflict,
|
|
||||||
type WecomSyncSummary,
|
|
||||||
unwrap,
|
|
||||||
} from '@/api/training'
|
|
||||||
|
|
||||||
const router = useRouter()
|
|
||||||
const loading = ref(false)
|
|
||||||
const saving = ref(false)
|
|
||||||
const members = ref<TrainingMember[]>([])
|
|
||||||
const platformUsers = ref<PlatformUser[]>([])
|
|
||||||
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
|
|
||||||
const roleDict = ref<TrainingRoleDef[]>([])
|
|
||||||
|
|
||||||
const rolesVisible = ref(false)
|
|
||||||
const activeMember = ref<TrainingMember | null>(null)
|
|
||||||
const roleSelection = ref<string[]>([])
|
|
||||||
|
|
||||||
// 企微账号绑定(培训提醒推送目标)
|
|
||||||
const wecomVisible = ref(false)
|
|
||||||
const activeWecomMember = ref<TrainingMember | null>(null)
|
|
||||||
const wecomInput = ref('')
|
|
||||||
const savingWecom = ref(false)
|
|
||||||
|
|
||||||
// OA 同步(工号 → 企微 userid,预览→写入两段式)
|
|
||||||
const syncVisible = ref(false)
|
|
||||||
const syncing = ref(false)
|
|
||||||
const syncSummary = ref<WecomSyncSummary | null>(null)
|
|
||||||
|
|
||||||
const conflictText = (cf: WecomSyncConflict) => {
|
|
||||||
switch (cf.reason) {
|
|
||||||
case 'duplicate_workcode_in_oa':
|
|
||||||
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
|
|
||||||
case 'bound_to_different_userid':
|
|
||||||
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
|
|
||||||
case 'userid_occupied':
|
|
||||||
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
|
|
||||||
default:
|
|
||||||
return cf.reason
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const onPreviewSync = async () => {
|
|
||||||
syncing.value = true
|
|
||||||
try {
|
|
||||||
const res = await previewWecomUseridSync()
|
|
||||||
syncSummary.value = unwrap(res) ?? null
|
|
||||||
syncVisible.value = true
|
|
||||||
} catch (err: any) {
|
|
||||||
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
|
|
||||||
} finally {
|
|
||||||
syncing.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const onApplySync = async () => {
|
|
||||||
syncing.value = true
|
|
||||||
try {
|
|
||||||
const res = await applyWecomUseridSync()
|
|
||||||
const summary = unwrap(res)
|
|
||||||
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
|
|
||||||
syncVisible.value = false
|
|
||||||
loadAll()
|
|
||||||
} catch (err: any) {
|
|
||||||
MessagePlugin.error(err?.response?.data?.message || '写入失败')
|
|
||||||
} finally {
|
|
||||||
syncing.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const memberColumns = [
|
|
||||||
{ colKey: 'employee_no', title: '工号', width: 100 },
|
|
||||||
{ colKey: 'user_name', title: '姓名' },
|
|
||||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
|
||||||
{ colKey: 'post', title: '岗位', width: 140 },
|
|
||||||
{ colKey: 'wecom_userid', title: '企微账号', width: 120 },
|
|
||||||
{ colKey: 'roles', title: '职称角色', width: 260 },
|
|
||||||
{ colKey: 'op', title: '操作', width: 170 },
|
|
||||||
]
|
|
||||||
|
|
||||||
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
|
|
||||||
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
|
|
||||||
|
|
||||||
// 跳转组织架构页(部门/员工档案的唯一维护入口)
|
|
||||||
const goOrgCenter = () => router.push('/platform/org-center')
|
|
||||||
|
|
||||||
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
|
||||||
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不再回退展示用户ID。
|
|
||||||
const userNameMap = computed(() => {
|
|
||||||
const m: Record<string, string> = {}
|
|
||||||
for (const u of platformUsers.value) m[u.id] = u.display_name?.trim() || u.username
|
|
||||||
return m
|
|
||||||
})
|
|
||||||
const memberName = (row: TrainingMember) => row.user_name || userNameMap.value[row.user_id] || ''
|
|
||||||
|
|
||||||
const loadAll = async () => {
|
|
||||||
loading.value = true
|
|
||||||
try {
|
|
||||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
|
||||||
const [m, u] = await Promise.all([
|
|
||||||
listMembers({ page_size: 500 }),
|
|
||||||
listPlatformUsers().catch(() => null),
|
|
||||||
])
|
|
||||||
members.value = unwrap(m)?.items || []
|
|
||||||
platformUsers.value = unwrap(u) || []
|
|
||||||
} finally {
|
|
||||||
loading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const openRoles = (row: TrainingMember) => {
|
|
||||||
activeMember.value = row
|
|
||||||
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
|
|
||||||
rolesVisible.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const openWecom = (row: TrainingMember) => {
|
|
||||||
activeWecomMember.value = row
|
|
||||||
wecomInput.value = row.wecom_userid || ''
|
|
||||||
wecomVisible.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const onSaveWecom = async () => {
|
|
||||||
if (!activeWecomMember.value) return
|
|
||||||
savingWecom.value = true
|
|
||||||
try {
|
|
||||||
await updateMemberWecomUserid(activeWecomMember.value.id, wecomInput.value.trim())
|
|
||||||
MessagePlugin.success('企微账号已更新')
|
|
||||||
wecomVisible.value = false
|
|
||||||
loadAll()
|
|
||||||
} catch (err: any) {
|
|
||||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
|
||||||
} finally {
|
|
||||||
savingWecom.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const onSaveRoles = async () => {
|
|
||||||
if (!activeMember.value) return
|
|
||||||
saving.value = true
|
|
||||||
try {
|
|
||||||
await updateMemberRoles(activeMember.value.id, [...roleSelection.value, 'trainee'])
|
|
||||||
MessagePlugin.success('角色已更新')
|
|
||||||
rolesVisible.value = false
|
|
||||||
loadAll()
|
|
||||||
} catch (err: any) {
|
|
||||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
|
||||||
} finally {
|
|
||||||
saving.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
loadAll()
|
|
||||||
fetchRoleDict().then((d) => {
|
|
||||||
roleDict.value = d
|
|
||||||
})
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style lang="less" scoped>
|
|
||||||
@import (reference) '../training.less';
|
|
||||||
|
|
||||||
.panel-box {
|
|
||||||
.training-panel-box();
|
|
||||||
}
|
|
||||||
|
|
||||||
.member-panel__hint {
|
|
||||||
color: var(--td-text-color-placeholder);
|
|
||||||
font-size: var(--app-text-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.member-panel__link {
|
|
||||||
color: var(--td-brand-color);
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.role-tag { margin-right: 4px; }
|
|
||||||
.wecom-missing { color: var(--td-text-color-placeholder); }
|
|
||||||
.oa-sync-btn { margin-left: 12px; }
|
|
||||||
.sync-stats {
|
|
||||||
display: flex;
|
|
||||||
gap: 14px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
margin-bottom: 12px;
|
|
||||||
color: var(--td-text-color-secondary);
|
|
||||||
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
|
|
||||||
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
|
|
||||||
}
|
|
||||||
.sync-section {
|
|
||||||
margin-bottom: 12px;
|
|
||||||
max-height: 180px;
|
|
||||||
overflow: auto;
|
|
||||||
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
|
|
||||||
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
|
|
||||||
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
|
|
||||||
}
|
|
||||||
.sync-footer { display: flex; gap: 8px; justify-content: flex-end; }
|
|
||||||
.form-hint {
|
|
||||||
margin-top: 8px;
|
|
||||||
color: var(--td-text-color-placeholder);
|
|
||||||
font-size: var(--app-text-sm);
|
|
||||||
}
|
|
||||||
// 姓名列:最多展示 2 行,超出省略(悬停 tooltip 看全名)
|
|
||||||
.member-name {
|
|
||||||
display: -webkit-box;
|
|
||||||
-webkit-box-orient: vertical;
|
|
||||||
-webkit-line-clamp: 2;
|
|
||||||
overflow: hidden;
|
|
||||||
word-break: break-all;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -126,15 +126,24 @@
|
|||||||
:label="`${c.name}${c.category ? `(${c.category})` : ''}`"
|
:label="`${c.name}${c.category ? `(${c.category})` : ''}`"
|
||||||
/>
|
/>
|
||||||
</t-select>
|
</t-select>
|
||||||
|
<!-- 000158:提交时按名称精准匹配课程管理,未命中自动新增待核验课程 -->
|
||||||
|
<div class="form-hint">提交时按名称精准匹配课程管理;未匹配到将自动新增该课程(待审核),经课长/经理签核后方可发布</div>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="分类" name="category">
|
<t-form-item label="分类" name="category">
|
||||||
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
|
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="所属部门" name="dept_id">
|
<t-form-item label="所属部门" name="dept_id">
|
||||||
<t-input :value="deptDisplay" disabled placeholder="提交时按提报人所在部门自动获取" />
|
<!-- 000158:所属部门必须为填报人本人部门,服务端强制按提报人部门落库 -->
|
||||||
|
<t-input :value="deptDisplay" disabled placeholder="自动带出提报人所在部门(不可修改)" />
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="适合人员" name="post_scope">
|
<t-form-item label="适合人员" name="post_scope">
|
||||||
<t-input v-model="demandForm.post_scope" placeholder="可填写多个适合人员,用、或,分隔(选填)" />
|
<!-- 000159 部门多选口径:归属部门(可多选)或「全部」(互斥),自动建档随需求带入课程 -->
|
||||||
|
<t-select
|
||||||
|
v-model="demandSuitableList" clearable filterable multiple
|
||||||
|
placeholder="选择部门(可多选),或选「全部」(选填)" style="width: 100%"
|
||||||
|
>
|
||||||
|
<t-option v-for="opt in demandSuitableOptions" :key="opt" :value="opt" :label="opt" />
|
||||||
|
</t-select>
|
||||||
</t-form-item>
|
</t-form-item>
|
||||||
<t-form-item label="计划培训月份" name="planned_month">
|
<t-form-item label="计划培训月份" name="planned_month">
|
||||||
<t-select
|
<t-select
|
||||||
@@ -197,7 +206,7 @@
|
|||||||
:autosize="{ minRows: 6 }"
|
:autosize="{ minRows: 6 }"
|
||||||
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
|
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
|
||||||
/>
|
/>
|
||||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
|
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配)或外部讲师姓名;部门列必须为导入人本人部门,留空默认本人部门,其余部门整批拒绝导入;课程按名称精准匹配课程管理,未匹配到自动新增该课程(待审核);导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
|
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
|
||||||
</template>
|
</template>
|
||||||
@@ -235,7 +244,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
import { MessagePlugin } from 'tdesign-vue-next'
|
import { MessagePlugin } from 'tdesign-vue-next'
|
||||||
import * as XLSX from 'xlsx'
|
import * as XLSX from 'xlsx'
|
||||||
import { fmtBeijingTime } from '@/utils/datetime'
|
import { fmtBeijingTime } from '@/utils/datetime'
|
||||||
@@ -332,13 +341,35 @@ const demandForm = ref({
|
|||||||
remark: '',
|
remark: '',
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 适合人员多选值(000159 部门多选口径):form.post_scope 存「、」join 后的串,
|
||||||
|
// 选项交互走本数组;「全部」与具体部门互斥。
|
||||||
|
const demandSuitableList = ref<string[]>([])
|
||||||
|
const splitSuitable = (v: string) =>
|
||||||
|
(v || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
|
||||||
|
watch(demandSuitableList, (list, prev) => {
|
||||||
|
if (list.includes('全部') && list.length > 1) {
|
||||||
|
demandSuitableList.value = (prev || []).includes('全部') ? list.filter((v) => v !== '全部') : ['全部']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// 适合人员选项:全部 + 各部门名(存量自由文本值保留可选)
|
||||||
|
const demandSuitableOptions = computed(() => {
|
||||||
|
const opts = ['全部', ...depts.value.map((d) => d.name)]
|
||||||
|
for (const v of splitSuitable(demandForm.value.post_scope)) {
|
||||||
|
if (!opts.includes(v)) opts.push(v)
|
||||||
|
}
|
||||||
|
return opts
|
||||||
|
})
|
||||||
|
|
||||||
// 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改;
|
// 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改;
|
||||||
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
|
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
|
||||||
const onDemandCourseChange = (name: unknown) => {
|
const onDemandCourseChange = (name: unknown) => {
|
||||||
const course = libraryCourses.value.find((c) => c.name === name)
|
const course = libraryCourses.value.find((c) => c.name === name)
|
||||||
if (!course) return
|
if (!course) return
|
||||||
demandForm.value.category = course.category || ''
|
demandForm.value.category = course.category || ''
|
||||||
if (course.suitable_members) demandForm.value.post_scope = course.suitable_members
|
if (course.suitable_members) {
|
||||||
|
demandForm.value.post_scope = course.suitable_members
|
||||||
|
demandSuitableList.value = splitSuitable(course.suitable_members)
|
||||||
|
}
|
||||||
const lecturerValue = course.lecturer_id || course.lecturer_external || ''
|
const lecturerValue = course.lecturer_id || course.lecturer_external || ''
|
||||||
if (lecturerValue) {
|
if (lecturerValue) {
|
||||||
if (!lecturers.value.some((l) => l.id === lecturerValue)) {
|
if (!lecturers.value.some((l) => l.id === lecturerValue)) {
|
||||||
@@ -552,6 +583,7 @@ const onOpenDemandForm = () => {
|
|||||||
lecturer: '',
|
lecturer: '',
|
||||||
remark: '',
|
remark: '',
|
||||||
}
|
}
|
||||||
|
demandSuitableList.value = []
|
||||||
demandFormVisible.value = true
|
demandFormVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -588,6 +620,8 @@ const onEditDemand = (row: TrainingDemand) => {
|
|||||||
lecturer: lecturerValue,
|
lecturer: lecturerValue,
|
||||||
remark: row.remark || '',
|
remark: row.remark || '',
|
||||||
}
|
}
|
||||||
|
// 适合人员多选回显(000159):落库串「、」join → 数组
|
||||||
|
demandSuitableList.value = splitSuitable(demandForm.value.post_scope)
|
||||||
demandFormVisible.value = true
|
demandFormVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -599,10 +633,14 @@ const onSaveDemand = async () => {
|
|||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
|
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
|
||||||
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名
|
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名;
|
||||||
|
// 适合人员多选 → 「、」join 落库(000159)
|
||||||
const { lecturer, planned_month, ...rest } = demandForm.value
|
const { lecturer, planned_month, ...rest } = demandForm.value
|
||||||
|
rest.post_scope = demandSuitableList.value.join('、')
|
||||||
const month = Number(planned_month) || 0
|
const month = Number(planned_month) || 0
|
||||||
const isEdit = Boolean(demandForm.value.id)
|
const isEdit = Boolean(demandForm.value.id)
|
||||||
|
// 课程管理中是否已有同名课程(000158:无则提交时自动新增待核验课程)
|
||||||
|
const courseExisted = libraryCourses.value.some((c) => c.name === demandForm.value.course_name)
|
||||||
await saveDemand({
|
await saveDemand({
|
||||||
...rest,
|
...rest,
|
||||||
...resolveLecturer(lecturer),
|
...resolveLecturer(lecturer),
|
||||||
@@ -612,7 +650,13 @@ const onSaveDemand = async () => {
|
|||||||
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
|
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
|
||||||
year: selectedYear.value,
|
year: selectedYear.value,
|
||||||
})
|
})
|
||||||
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待核验')
|
MessagePlugin.success(
|
||||||
|
demandForm.value.id
|
||||||
|
? '需求已更新'
|
||||||
|
: courseExisted
|
||||||
|
? '需求已提交,待核验'
|
||||||
|
: `需求已提交,待核验;课程《${demandForm.value.course_name}》已自动新增到课程管理(待审核)`,
|
||||||
|
)
|
||||||
demandFormVisible.value = false
|
demandFormVisible.value = false
|
||||||
loadAll()
|
loadAll()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -668,8 +712,9 @@ const onImportDemands = async () => {
|
|||||||
importDemandsVisible.value = false
|
importDemandsVisible.value = false
|
||||||
importDemandsText.value = ''
|
importDemandsText.value = ''
|
||||||
loadAll()
|
loadAll()
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
MessagePlugin.error('导入失败,请检查格式')
|
// 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '导入失败,请检查格式'))
|
||||||
} finally {
|
} finally {
|
||||||
saving.value = false
|
saving.value = false
|
||||||
}
|
}
|
||||||
@@ -747,7 +792,8 @@ const onImportDemandExcel = async (e: Event) => {
|
|||||||
let skippedRows = 0
|
let skippedRows = 0
|
||||||
let lecturerHits = 0
|
let lecturerHits = 0
|
||||||
let externalLecturers = 0
|
let externalLecturers = 0
|
||||||
let deptFromLecturer = 0
|
// 部门口径(000158):Excel 全部行必须为导入人本人部门,前端预检不过不提交
|
||||||
|
const deptViolations: string[] = []
|
||||||
// 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案),
|
// 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案),
|
||||||
// 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示
|
// 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示
|
||||||
const ensureMembers = async () => {
|
const ensureMembers = async () => {
|
||||||
@@ -763,24 +809,23 @@ const onImportDemandExcel = async (e: Event) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
await ensureMembers()
|
await ensureMembers()
|
||||||
dataRows.forEach((row) => {
|
dataRows.forEach((row, idx) => {
|
||||||
const courseName = (row['课程名称'] || '').trim()
|
const courseName = (row['课程名称'] || '').trim()
|
||||||
if (!courseName) {
|
if (!courseName) {
|
||||||
skippedRows += 1
|
skippedRows += 1
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;未匹配留空
|
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;
|
||||||
|
// 000158:行部门必须为导入人本人部门——非空但未匹配到、或与本人部门
|
||||||
|
// 不一致即记违规,整批拒绝;部门列留空的行由后端默认导入人部门。
|
||||||
let deptId = ''
|
let deptId = ''
|
||||||
let deptMatched = false
|
|
||||||
const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim()
|
const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim()
|
||||||
if (deptName) {
|
if (deptName) {
|
||||||
const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
|
const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
|
||||||
if (hit) {
|
if (hit) deptId = hit.id
|
||||||
deptId = hit.id
|
if (!deptId || deptId !== myDeptId.value) deptViolations.push(`第${idx + 1}行(${deptName})`)
|
||||||
deptMatched = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名,行内部门未匹配时带出讲师部门;
|
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名;
|
||||||
// 非系统员工→落外部讲师姓名,讲师列照常显示
|
// 非系统员工→落外部讲师姓名,讲师列照常显示
|
||||||
let lecturerId = ''
|
let lecturerId = ''
|
||||||
let lecturerExternal = ''
|
let lecturerExternal = ''
|
||||||
@@ -790,10 +835,6 @@ const onImportDemandExcel = async (e: Event) => {
|
|||||||
if (hit && hit.user_id) {
|
if (hit && hit.user_id) {
|
||||||
lecturerId = hit.user_id
|
lecturerId = hit.user_id
|
||||||
lecturerHits += 1
|
lecturerHits += 1
|
||||||
if (!deptMatched && hit.dept_id) {
|
|
||||||
deptId = hit.dept_id
|
|
||||||
deptFromLecturer += 1
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
lecturerExternal = lecturerName
|
lecturerExternal = lecturerName
|
||||||
externalLecturers += 1
|
externalLecturers += 1
|
||||||
@@ -813,6 +854,7 @@ const onImportDemandExcel = async (e: Event) => {
|
|||||||
lecturer_id: lecturerId,
|
lecturer_id: lecturerId,
|
||||||
lecturer_external: lecturerExternal || undefined,
|
lecturer_external: lecturerExternal || undefined,
|
||||||
dept_id: deptId,
|
dept_id: deptId,
|
||||||
|
dept_name: deptName || undefined,
|
||||||
planned_time: plannedMonth.planned || undefined,
|
planned_time: plannedMonth.planned || undefined,
|
||||||
expect_month: plannedMonth.month || undefined,
|
expect_month: plannedMonth.month || undefined,
|
||||||
remark: (row['备注'] || '').trim(),
|
remark: (row['备注'] || '').trim(),
|
||||||
@@ -822,24 +864,36 @@ const onImportDemandExcel = async (e: Event) => {
|
|||||||
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
|
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 000158:存在非本人部门的行时整批拒绝(后端同口径兜底校验)
|
||||||
|
if (deptViolations.length) {
|
||||||
|
MessagePlugin.error(
|
||||||
|
`导入失败:${deptViolations.join('、')}部门与您所在部门(${myDeptName.value || '未知'})不一致,仅可导入本人部门的需求表`,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const imported = unwrap(await importDemands(items)) as { imported: number; notified?: number } | null
|
const imported = unwrap(await importDemands(items)) as {
|
||||||
|
imported: number
|
||||||
|
notified?: number
|
||||||
|
courses_created?: number
|
||||||
|
} | null
|
||||||
MessagePlugin.success(
|
MessagePlugin.success(
|
||||||
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
|
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
|
||||||
(lecturerHits || externalLecturers
|
(lecturerHits || externalLecturers
|
||||||
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
|
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
|
||||||
: '') +
|
: '') +
|
||||||
(deptFromLecturer ? `(其中 ${deptFromLecturer} 条部门按讲师带出)` : '') +
|
|
||||||
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
|
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
|
||||||
|
(imported?.courses_created ? `,自动新增待审核课程 ${imported.courses_created} 门` : '') +
|
||||||
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
|
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
|
||||||
)
|
)
|
||||||
importDemandsVisible.value = false
|
importDemandsVisible.value = false
|
||||||
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
|
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
|
||||||
if (titleYear !== selectedYear.value) selectedYear.value = titleYear
|
if (titleYear !== selectedYear.value) selectedYear.value = titleYear
|
||||||
loadAll()
|
loadAll()
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
MessagePlugin.error('导入失败,请稍后重试')
|
// 透出后端校验详情(000158:部门归属/课程自动匹配等口径错误)
|
||||||
|
MessagePlugin.error(apiErrorMessage(e, '导入失败,请稍后重试'))
|
||||||
} finally {
|
} finally {
|
||||||
saving.value = false
|
saving.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,15 +65,25 @@ func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, i
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
|
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
|
||||||
|
// users/org_depts 联查在此一并挂上:keyword 需要按姓名/部门名过滤,且 Count
|
||||||
|
// 与列表共用同一过滤,联查必须两边一致(users/org_depts 对档案均为 1:1,
|
||||||
|
// 不影响 Count 语义)。
|
||||||
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
|
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
|
||||||
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).Where("org_employees.tenant_id = ?", tenantID)
|
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
||||||
|
Where("org_employees.tenant_id = ?", tenantID).
|
||||||
|
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
||||||
|
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
||||||
if q != nil {
|
if q != nil {
|
||||||
if q.DeptID != "" {
|
if q.DeptID != "" {
|
||||||
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
||||||
}
|
}
|
||||||
if q.Keyword != "" {
|
if q.Keyword != "" {
|
||||||
tx = tx.Where("org_employees.employee_no ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
// 按姓名/工号/部门名/岗位模糊查找;姓名取真实姓名(display_name)
|
||||||
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
// 回退平台账号(username),与列表展示口径一致。
|
||||||
|
tx = tx.Where(
|
||||||
|
"org_employees.employee_no ILIKE ? OR COALESCE(NULLIF(u.display_name, ''), u.username, '') ILIKE ? "+
|
||||||
|
"OR COALESCE(dp.name, '') ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
||||||
|
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return tx
|
return tx
|
||||||
@@ -102,9 +112,7 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
|
|||||||
tx := filter().
|
tx := filter().
|
||||||
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
||||||
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
||||||
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`).
|
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`)
|
||||||
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
|
||||||
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
|
||||||
if moduleKey != "" {
|
if moduleKey != "" {
|
||||||
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
||||||
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
|
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
|
||||||
@@ -112,8 +120,9 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
|
|||||||
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
|
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
|
||||||
}
|
}
|
||||||
var employees []*types.OrgEmployee
|
var employees []*types.OrgEmployee
|
||||||
|
// 新增成员置顶(时间倒序):最新建档/导入的员工排在列表最前。
|
||||||
err := tx.
|
err := tx.
|
||||||
Order("org_employees.created_at ASC").
|
Order("org_employees.created_at DESC").
|
||||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||||
Find(&employees).Error
|
Find(&employees).Error
|
||||||
return employees, total, err
|
return employees, total, err
|
||||||
@@ -141,6 +150,27 @@ func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID
|
|||||||
return &m, nil
|
return &m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InsertEmployeesIfAbsent 自动入册专用:成员加入空间时补建员工档案。
|
||||||
|
// 与 UpsertEmployees(导入语义,整行覆盖)不同,本方法只补空不覆盖——
|
||||||
|
// 已有档案的工号/部门仅在为空时用新值回填(如 Casdoor 后同步到部门),
|
||||||
|
// 人工维护过(或 OA 同步)的字段一律保留。
|
||||||
|
func (r *orgCenterRepository) InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||||
|
if len(employees) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return r.db.WithContext(ctx).
|
||||||
|
Clauses(clause.OnConflict{
|
||||||
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
||||||
|
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||||
|
// 档案已有工号/部门时不覆盖(空串/空 id 视为未维护,由新值补齐)。
|
||||||
|
"employee_no": gorm.Expr("COALESCE(NULLIF(org_employees.employee_no, ''), EXCLUDED.employee_no)"),
|
||||||
|
"dept_id": gorm.Expr("COALESCE(NULLIF(org_employees.dept_id, ''), EXCLUDED.dept_id)"),
|
||||||
|
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||||
|
}),
|
||||||
|
}).
|
||||||
|
Create(&employees).Error
|
||||||
|
}
|
||||||
|
|
||||||
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
|
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
|
||||||
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||||
if len(employees) == 0 {
|
if len(employees) == 0 {
|
||||||
@@ -218,6 +248,31 @@ func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint
|
|||||||
return users, err
|
return users, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListAdoptableUsers lists the tenant's active members whose home tenant
|
||||||
|
// (users.tenant_id) is not this workspace — the preview source for
|
||||||
|
// 「收编到本空间」. 归属列为 NULL(无归属账号)的成员同样是候选:Postgres 的
|
||||||
|
// `NULL != x` 不命中,须 COALESCE 兜底(仓库测试跑在 SQLite 上,两者兼容)。
|
||||||
|
// 名册 join 与 ListTenantUsers 同口径;home 租户名联查 tenants(带软删过滤)
|
||||||
|
// 供 UI 确认来源空间。
|
||||||
|
func (r *orgCenterRepository) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) {
|
||||||
|
var users []*types.OrgAdoptableUser
|
||||||
|
err := r.db.WithContext(ctx).
|
||||||
|
Table("users u").
|
||||||
|
Select(`u.id, u.username, u.email, u.display_name,
|
||||||
|
COALESCE(u.tenant_id, 0) AS home_tenant_id,
|
||||||
|
COALESCE(ht.name, '') AS home_tenant_name,
|
||||||
|
(m.id IS NOT NULL) AS in_roster`).
|
||||||
|
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
|
||||||
|
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
|
||||||
|
Joins("LEFT JOIN org_employees m ON m.user_id = u.id AND m.tenant_id = ? AND m.deleted_at IS NULL", tenantID).
|
||||||
|
Joins("LEFT JOIN tenants ht ON ht.id = u.tenant_id AND ht.deleted_at IS NULL").
|
||||||
|
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
||||||
|
Where("COALESCE(u.tenant_id, 0) != ?", tenantID).
|
||||||
|
Order("u.created_at ASC").
|
||||||
|
Scan(&users).Error
|
||||||
|
return users, err
|
||||||
|
}
|
||||||
|
|
||||||
// GetUsernamesByUserIDs resolves platform accounts (users.username) for the
|
// GetUsernamesByUserIDs resolves platform accounts (users.username) for the
|
||||||
// given user IDs within the tenant — used to backfill employee_no on import
|
// given user IDs within the tenant — used to backfill employee_no on import
|
||||||
// (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。
|
// (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。
|
||||||
@@ -244,6 +299,26 @@ func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantI
|
|||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRosterUserInfos resolves the roster-relevant user fields (平台账号 + Casdoor
|
||||||
|
// 同步部门) for the given user IDs within the tenant — source for auto-creating
|
||||||
|
// employee profiles when members join (EnsureEmployeesForUsers 的取数口径与
|
||||||
|
// GetUsernamesByUserIDs 一致:本空间 active 成员)。
|
||||||
|
func (r *orgCenterRepository) GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var users []*types.TrainingUserInfo
|
||||||
|
err := r.db.WithContext(ctx).
|
||||||
|
Table("users u").
|
||||||
|
Select("u.id, u.username, u.dept_code, u.dept_name").
|
||||||
|
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
|
||||||
|
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
|
||||||
|
Where("u.id IN ?", userIDs).
|
||||||
|
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
||||||
|
Scan(&users).Error
|
||||||
|
return users, err
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 模块角色绑定
|
// 模块角色绑定
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"academy/internal/types"
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 收编预览数据源回归:ListAdoptableUsers 须列出「归属空间不在本空间」的活跃
|
||||||
|
// 成员,含两类边界——归属列为 NULL 的无归属账号(Postgres 的 `NULL != x` 不
|
||||||
|
// 命中,COALESCE 兜底)与归属本空间者不列。名册标记与 home 租户名供 UI 确认。
|
||||||
|
func TestListAdoptableUsers(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open("file:org-adoptable?mode=memory&cache=shared"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&types.User{}, &types.Tenant{}, &types.TenantMember{}, &types.OrgEmployee{}); err != nil {
|
||||||
|
t.Fatalf("migrate schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
base := time.Date(2026, 11, 24, 3, 0, 0, 0, time.UTC)
|
||||||
|
mkUser := func(id string, home uint64, offset time.Duration) *types.User {
|
||||||
|
return &types.User{
|
||||||
|
ID: id, Username: id, Email: id + "@casdoor.local",
|
||||||
|
TenantID: home, IsActive: true,
|
||||||
|
CreatedAt: base.Add(offset), UpdatedAt: base.Add(offset),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// personal-home:归属个人空间 3,典型收编对象;tenantless:归属 NULL;
|
||||||
|
// local:归属本空间 2(不列);inactive:停用账号不列。
|
||||||
|
for _, u := range []*types.User{
|
||||||
|
mkUser("personal-home", 3, 0),
|
||||||
|
mkUser("tenantless", 0, time.Hour),
|
||||||
|
mkUser("local", 2, 2*time.Hour),
|
||||||
|
mkUser("inactive", 4, 3*time.Hour),
|
||||||
|
} {
|
||||||
|
if err := db.Create(u).Error; err != nil {
|
||||||
|
t.Fatalf("insert user %s: %v", u.ID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 停用账号以软删模拟(与 GetUsersByIDs/ListTenantUsers 的可见口径一致)。
|
||||||
|
if err := db.Delete(&types.User{}, "id = ?", "inactive").Error; err != nil {
|
||||||
|
t.Fatalf("soft-delete user: %v", err)
|
||||||
|
}
|
||||||
|
for _, m := range []*types.TenantMember{
|
||||||
|
{UserID: "personal-home", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base},
|
||||||
|
{UserID: "tenantless", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(time.Hour)},
|
||||||
|
{UserID: "local", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(2 * time.Hour)},
|
||||||
|
{UserID: "inactive", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(3 * time.Hour)},
|
||||||
|
} {
|
||||||
|
if err := db.Create(m).Error; err != nil {
|
||||||
|
t.Fatalf("insert membership %s: %v", m.UserID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := db.Create(&types.Tenant{ID: 3, Name: "26080007's Workspace", Status: "active"}).Error; err != nil {
|
||||||
|
t.Fatalf("insert home tenant: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&types.OrgEmployee{
|
||||||
|
TenantID: 2, UserID: "personal-home", EmployeeNo: "26080007", Status: "active",
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("insert roster entry: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := &orgCenterRepository{db: db}
|
||||||
|
users, err := repo.ListAdoptableUsers(context.Background(), 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListAdoptableUsers: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
byID := map[string]*types.OrgAdoptableUser{}
|
||||||
|
for _, u := range users {
|
||||||
|
byID[u.ID] = u
|
||||||
|
}
|
||||||
|
if len(users) != 2 {
|
||||||
|
t.Fatalf("want exactly personal-home + tenantless, got %+v", users)
|
||||||
|
}
|
||||||
|
if u := byID["personal-home"]; u == nil {
|
||||||
|
t.Fatal("personal-home missing from adoptable list")
|
||||||
|
} else {
|
||||||
|
if u.HomeTenantID != 3 || u.HomeTenantName != "26080007's Workspace" {
|
||||||
|
t.Fatalf("personal-home home = %d/%q, want 3/26080007's Workspace", u.HomeTenantID, u.HomeTenantName)
|
||||||
|
}
|
||||||
|
if !u.InRoster {
|
||||||
|
t.Fatal("personal-home InRoster = false, want true")
|
||||||
|
}
|
||||||
|
if u.Username != "personal-home" || u.Email != "personal-home@casdoor.local" {
|
||||||
|
t.Fatalf("personal-home display fields wrong: %+v", u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if u := byID["tenantless"]; u == nil {
|
||||||
|
t.Fatal("tenantless (NULL home) missing from adoptable list — COALESCE guard failed")
|
||||||
|
} else if u.HomeTenantID != 0 || u.HomeTenantName != "" {
|
||||||
|
t.Fatalf("tenantless home should be 0/'', got %d/%q", u.HomeTenantID, u.HomeTenantName)
|
||||||
|
}
|
||||||
|
for _, absent := range []string{"local", "inactive"} {
|
||||||
|
if byID[absent] != nil {
|
||||||
|
t.Fatalf("user %s must not appear in adoptable list", absent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,6 +48,25 @@ func (r *trainingRepository) GetMemberByUserID(ctx context.Context, tenantID uin
|
|||||||
return &m, nil
|
return &m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160):
|
||||||
|
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
|
||||||
|
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
|
||||||
|
// 同一组织的人员不因所在工作区不同而看不到企业培训。无档案返回 0,nil。
|
||||||
|
func (r *trainingRepository) FindArchiveTenantID(ctx context.Context, userID string) (uint64, error) {
|
||||||
|
var tenantIDs []uint64
|
||||||
|
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
||||||
|
Where("user_id = ? AND status = ?", userID, "active").
|
||||||
|
Order("created_at ASC").Limit(1).
|
||||||
|
Pluck("tenant_id", &tenantIDs).Error
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if len(tenantIDs) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return tenantIDs[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 学习/积分/规则/通知
|
// 学习/积分/规则/通知
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -31,6 +31,21 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
|||||||
if q.RelatedUserID != "" {
|
if q.RelatedUserID != "" {
|
||||||
tx = tx.Where("tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?", q.RelatedUserID, q.RelatedUserID)
|
tx = tx.Where("tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?", q.RelatedUserID, q.RelatedUserID)
|
||||||
}
|
}
|
||||||
|
// 学员目录口径(000160,scope=catalog):仅已发布 + 适合人员覆盖调用方。
|
||||||
|
// suitable='全部' 全员可见;000159 多部门口径:值按「、」拆分(逗号/分号
|
||||||
|
// 兼容归一)后与调用方部门名做成员匹配;未设置适合人员的存量课程沿用
|
||||||
|
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。调用方
|
||||||
|
// 无部门档案时只见「全部」与未设置的课程。
|
||||||
|
if q.CatalogOnly {
|
||||||
|
tx = tx.Where("tr_course_library.publish_status = ?", "published")
|
||||||
|
tx = tx.Where(
|
||||||
|
"tr_course_library.suitable_members = ? "+
|
||||||
|
"OR (? <> '' AND ? = ANY(string_to_array(replace(replace(replace(replace(tr_course_library.suitable_members, ',', '、'), ',', '、'), ';', '、'), ';', '、'), '、'))) "+
|
||||||
|
"OR (tr_course_library.suitable_members = '' AND (tr_course_library.owner_dept_id = '' "+
|
||||||
|
"OR (? <> '' AND tr_course_library.owner_dept_id = ?)))",
|
||||||
|
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var total int64
|
var total int64
|
||||||
if err := tx.Count(&total).Error; err != nil {
|
if err := tx.Count(&total).Error; err != nil {
|
||||||
@@ -59,6 +74,19 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
|||||||
return items, total, err
|
return items, total, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FindCourseLibraryByName fetches one course-library item by exact course name
|
||||||
|
// (需求侧课程自动匹配,000158:按课程名称精准查找,同名存量取最早一条)。
|
||||||
|
func (r *trainingRepository) FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error) {
|
||||||
|
var item types.TrainingCourseLibrary
|
||||||
|
if err := r.db.WithContext(ctx).
|
||||||
|
Where("tenant_id = ? AND name = ?", tenantID, name).
|
||||||
|
Order("created_at ASC").
|
||||||
|
First(&item).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &item, nil
|
||||||
|
}
|
||||||
|
|
||||||
// GetCourseLibraryItem fetches one course-library item.
|
// GetCourseLibraryItem fetches one course-library item.
|
||||||
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||||
var item types.TrainingCourseLibrary
|
var item types.TrainingCourseLibrary
|
||||||
|
|||||||
@@ -119,6 +119,7 @@ func (r *trainingRepository) UpdateDemand(ctx context.Context, demand *types.Tra
|
|||||||
"lecturer_id": demand.LecturerID,
|
"lecturer_id": demand.LecturerID,
|
||||||
"lecturer_external": demand.LecturerExternal,
|
"lecturer_external": demand.LecturerExternal,
|
||||||
"course_name": demand.CourseName,
|
"course_name": demand.CourseName,
|
||||||
|
"library_course_id": demand.LibraryCourseID,
|
||||||
"plant": demand.Plant,
|
"plant": demand.Plant,
|
||||||
"category": demand.Category,
|
"category": demand.Category,
|
||||||
"session_count": demand.SessionCount,
|
"session_count": demand.SessionCount,
|
||||||
@@ -527,6 +528,18 @@ func (r *trainingRepository) CountEnrolledMembersByCourse(ctx context.Context, t
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CountEnrolledMembersByCourseID 单课程的场次学员名单人数(发布必填校验用,
|
||||||
|
// 000161:跨场次名单去重成员数;与 CountEnrolledMembersByCourse 同口径)。
|
||||||
|
func (r *trainingRepository) CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error) {
|
||||||
|
var cnt int64
|
||||||
|
err := r.db.WithContext(ctx).
|
||||||
|
Table("tr_enrollments e").
|
||||||
|
Joins("JOIN tr_course_sessions s ON s.id = e.session_id AND s.tenant_id = e.tenant_id AND s.deleted_at IS NULL").
|
||||||
|
Where("e.tenant_id = ? AND s.course_id = ?", tenantID, courseID).
|
||||||
|
Count(&cnt).Error
|
||||||
|
return int(cnt), err
|
||||||
|
}
|
||||||
|
|
||||||
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(去重成员集合):
|
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(去重成员集合):
|
||||||
// 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷
|
// 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷
|
||||||
// (session 为空时经 paper→bank→course 兜底)两条路径。
|
// (session 为空时经 paper→bank→course 兜底)两条路径。
|
||||||
|
|||||||
@@ -119,9 +119,16 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
|
|||||||
// 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default
|
// 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default
|
||||||
// 优先,否则该类型第一个 active)。fail-open:解析不到保持为空,
|
// 优先,否则该类型第一个 active)。fail-open:解析不到保持为空,
|
||||||
// 运行时的 "chat model is not configured" 报错行为与现状一致。
|
// 运行时的 "chat model is not configured" 报错行为与现状一致。
|
||||||
if strings.TrimSpace(agent.Config.ModelID) == "" && s.modelService != nil {
|
// ReRank 同口径兜底:无可用重排模型时保持为空(按需运行,不阻断)。
|
||||||
|
if s.modelService != nil &&
|
||||||
|
(strings.TrimSpace(agent.Config.ModelID) == "" || strings.TrimSpace(agent.Config.RerankModelID) == "") {
|
||||||
if models, err := s.modelService.ListModels(ctx); err == nil {
|
if models, err := s.modelService.ListModels(ctx); err == nil {
|
||||||
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
|
if strings.TrimSpace(agent.Config.ModelID) == "" {
|
||||||
|
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(agent.Config.RerankModelID) == "" {
|
||||||
|
agent.Config.RerankModelID = PickDefaultModelID(models, types.ModelTypeRerank)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err)
|
logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"academy/internal/errors"
|
"academy/internal/errors"
|
||||||
"academy/internal/logger"
|
"academy/internal/logger"
|
||||||
@@ -10,16 +13,29 @@ import (
|
|||||||
"academy/internal/types/interfaces"
|
"academy/internal/types/interfaces"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
// orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。
|
// orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。
|
||||||
// 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色,
|
// 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色,
|
||||||
// 部门/岗位/姓名只维护一份。
|
// 部门/岗位/姓名只维护一份。
|
||||||
type orgCenterService struct {
|
type orgCenterService struct {
|
||||||
repo interfaces.OrgCenterRepository
|
repo interfaces.OrgCenterRepository
|
||||||
|
// 收编归属空间(登录默认落点)所需依赖。依赖仓库(UserRepository/
|
||||||
|
// TenantMemberRepository)而非服务:tenantMemberService 已反向依赖本服务,
|
||||||
|
// userService 又依赖 memberService,引用服务层会成 DI 环。audit 可空
|
||||||
|
// (nil ⇒ 不写审计,业务照常);users/members 为 nil 时收编接口不可用。
|
||||||
|
users interfaces.UserRepository
|
||||||
|
members interfaces.TenantMemberRepository
|
||||||
|
audit interfaces.AuditLogService
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewOrgCenterService constructs the org center service.
|
// NewOrgCenterService constructs the org center service.
|
||||||
func NewOrgCenterService(repo interfaces.OrgCenterRepository) interfaces.OrgCenterService {
|
func NewOrgCenterService(
|
||||||
return &orgCenterService{repo: repo}
|
repo interfaces.OrgCenterRepository,
|
||||||
|
users interfaces.UserRepository,
|
||||||
|
members interfaces.TenantMemberRepository,
|
||||||
|
audit interfaces.AuditLogService,
|
||||||
|
) interfaces.OrgCenterService {
|
||||||
|
return &orgCenterService{repo: repo, users: users, members: members, audit: audit}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -161,6 +177,66 @@ func firstDuplicateEmployeeNo(employees []*types.OrgEmployee) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EnsureEmployeesForUsers 成员加入空间时自动入册(需求:平台新增成员自动添加
|
||||||
|
// 到组织架构并匹配部门):按平台账号补建员工档案,部门按 Casdoor 同步字段
|
||||||
|
// 自动匹配(dept_code 精确命中优先,dept_name 兜底;匹配范式与 Casdoor 同步
|
||||||
|
// syncDepts 一致:小写去空格精确匹配)。档案已存在的成员跳过(仅补空),人工
|
||||||
|
// 维护字段不被覆盖。fail-open:入册是成员加入的伴生动作,失败只记日志,
|
||||||
|
// 不阻断成员关系本身。
|
||||||
|
func (s *orgCenterService) EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error {
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
users, err := s.repo.GetRosterUserInfos(ctx, tenantID, userIDs)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(users) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
depts, err := s.repo.ListDepts(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
byCode := make(map[string]string, len(depts))
|
||||||
|
byName := make(map[string]string, len(depts))
|
||||||
|
for _, d := range depts {
|
||||||
|
if code := strings.ToLower(strings.TrimSpace(d.Code)); code != "" {
|
||||||
|
byCode[code] = d.ID
|
||||||
|
}
|
||||||
|
if name := strings.ToLower(strings.TrimSpace(d.Name)); name != "" {
|
||||||
|
if _, exists := byName[name]; !exists {
|
||||||
|
byName[name] = d.ID // 首见优先,与 ListDepts 的 sort/created_at 序一致
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
employees := make([]*types.OrgEmployee, 0, len(users))
|
||||||
|
for _, u := range users {
|
||||||
|
deptID := ""
|
||||||
|
if code := strings.ToLower(strings.TrimSpace(u.DeptCode)); code != "" {
|
||||||
|
deptID = byCode[code]
|
||||||
|
}
|
||||||
|
if deptID == "" {
|
||||||
|
if name := strings.ToLower(strings.TrimSpace(u.DeptName)); name != "" {
|
||||||
|
deptID = byName[name]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
employees = append(employees, &types.OrgEmployee{
|
||||||
|
ID: orgCenterNewID(),
|
||||||
|
TenantID: tenantID,
|
||||||
|
UserID: u.ID,
|
||||||
|
EmployeeNo: u.Username, // 工号 = 平台账号(与导入回填同约定)
|
||||||
|
DeptID: deptID, // 未匹配到已维护部门时留空,可后续手动修改
|
||||||
|
Status: "active",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if err := s.repo.InsertEmployeesIfAbsent(ctx, employees); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "[OrgCenter] members auto-rostered, tenant=%d count=%d", tenantID, len(employees))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateEmployee updates one employee profile.
|
// UpdateEmployee updates one employee profile.
|
||||||
func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) {
|
func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) {
|
||||||
if employee.ID == "" {
|
if employee.ID == "" {
|
||||||
@@ -199,6 +275,135 @@ func (s *orgCenterService) ListTenantUsers(ctx context.Context, tenantID uint64)
|
|||||||
return s.repo.ListTenantUsers(ctx, tenantID)
|
return s.repo.ListTenantUsers(ctx, tenantID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 收编归属空间(登录默认落点)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。
|
||||||
|
func (s *orgCenterService) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) {
|
||||||
|
return s.repo.ListAdoptableUsers(ctx, tenantID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdoptHomeTenant 把指定成员的归属空间(users.tenant_id,登录/refresh 默认落点)
|
||||||
|
// 批量收编为本空间。场景:员工首登自动开通个人空间(auth.default_tenant_mode
|
||||||
|
// =create_personal 默认),归属指针停在个人空间,登录后看到的组织架构/培训
|
||||||
|
// 数据是个人空间里那份空数据;管理员在本空间维护好组织架构后,用收编把成员
|
||||||
|
// 的默认落点改回本空间。语义:
|
||||||
|
// - 只动归属指针与「最近活跃租户」偏好,成员关系/角色/个人空间数据都不变,
|
||||||
|
// 成员仍可经空间切换器自行改回,非破坏性;
|
||||||
|
// - 仅收编本空间活跃成员(逐条校验,缺失跳过并回传原因,不整批失败);
|
||||||
|
// - 跨空间账号(CanAccessAllTenants)不自动收编——其落点是刻意配置;
|
||||||
|
// - 同步「最近活跃租户」偏好指向本空间:登录路径(resolveLoginTenantID)
|
||||||
|
// 优先读偏好,只改归属不改偏好时,切过空间的成员下次登录仍落回旧空间;
|
||||||
|
// - 收编成功的成员补跑一次自动入册(仅补空、幂等),把同步部门带进名册;
|
||||||
|
// - 已有会话不受影响,自下次登录/refresh 起落到本空间。
|
||||||
|
func (s *orgCenterService) AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error) {
|
||||||
|
if tenantID == 0 {
|
||||||
|
return nil, errors.NewBadRequestError("缺少目标空间")
|
||||||
|
}
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
return nil, errors.NewBadRequestError("请选择要收编的成员")
|
||||||
|
}
|
||||||
|
if s.users == nil || s.members == nil {
|
||||||
|
return nil, errors.NewInternalServerError("收编功能不可用:依赖服务未装配")
|
||||||
|
}
|
||||||
|
result := &types.OrgAdoptResult{Skipped: []*types.OrgAdoptSkip{}}
|
||||||
|
adopted := make([]string, 0, len(userIDs))
|
||||||
|
for _, userID := range userIDs {
|
||||||
|
if s.adoptOneHomeTenant(ctx, tenantID, userID, result) == nil {
|
||||||
|
adopted = append(adopted, userID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.Adopted = len(adopted)
|
||||||
|
// 收编成功者补跑自动入册(fail-open,与成员加入路径同约定):名册缺行时
|
||||||
|
// 按平台账号补建,dept_code/dept_name 命中已维护部门时自动匹配。失败只
|
||||||
|
// 告警:归属指针已落库,名册可由成员加入路径或手动导入补齐。
|
||||||
|
if len(adopted) > 0 {
|
||||||
|
if err := s.EnsureEmployeesForUsers(ctx, tenantID, adopted); err != nil {
|
||||||
|
logger.Warnf(ctx, "[OrgCenter] adopt home tenant: auto-roster backfill failed (adoption kept): tenant=%d err=%v",
|
||||||
|
tenantID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.emitAdoptAudit(ctx, tenantID, len(adopted), result.Skipped)
|
||||||
|
logger.Infof(ctx, "[OrgCenter] home tenants adopted, tenant=%d adopted=%d skipped=%d",
|
||||||
|
tenantID, len(adopted), len(result.Skipped))
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// adoptOneHomeTenant 收编单个成员;返回 nil 表示收编成功,否则为跳过记录
|
||||||
|
// (已追加进 result.Skipped,原因逐条回传 UI)。
|
||||||
|
func (s *orgCenterService) adoptOneHomeTenant(ctx context.Context, tenantID uint64, userID string, result *types.OrgAdoptResult) *types.OrgAdoptSkip {
|
||||||
|
skipWith := func(u *types.User, reason string) *types.OrgAdoptSkip {
|
||||||
|
entry := &types.OrgAdoptSkip{UserID: userID, Reason: reason}
|
||||||
|
if u != nil {
|
||||||
|
entry.Username = u.Username
|
||||||
|
entry.DisplayName = u.DisplayName
|
||||||
|
}
|
||||||
|
result.Skipped = append(result.Skipped, entry)
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
user, err := s.users.GetUserByID(ctx, userID)
|
||||||
|
if err != nil || user == nil {
|
||||||
|
// GetUserByID 带软删过滤:已删除账号在此按不存在处理。
|
||||||
|
return skipWith(nil, "平台账号不存在")
|
||||||
|
}
|
||||||
|
if !user.IsActive {
|
||||||
|
return skipWith(user, "账号已停用")
|
||||||
|
}
|
||||||
|
if user.CanAccessAllTenants {
|
||||||
|
return skipWith(user, "跨空间账号不自动收编")
|
||||||
|
}
|
||||||
|
if user.TenantID == tenantID {
|
||||||
|
return skipWith(user, "归属空间已是本空间")
|
||||||
|
}
|
||||||
|
member, err := s.members.Get(ctx, userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return skipWith(user, "查询成员关系失败")
|
||||||
|
}
|
||||||
|
if member == nil || member.Status != types.TenantMemberStatusActive {
|
||||||
|
return skipWith(user, "非本空间成员,请先邀请或批量导入加入")
|
||||||
|
}
|
||||||
|
// 归属指针 + 最近活跃租户偏好一起指向本空间(见 AdoptHomeTenant 语义注释)。
|
||||||
|
user.TenantID = tenantID
|
||||||
|
user.Preferences.LastActiveTenantID = &tenantID
|
||||||
|
user.UpdatedAt = time.Now()
|
||||||
|
if err := s.users.UpdateUser(ctx, user); err != nil {
|
||||||
|
return skipWith(user, "写入归属空间失败:"+err.Error())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// emitAdoptAudit 写一条批量收编审计(best-effort:audit 不可用不阻断,
|
||||||
|
// 与 tenantMemberService.emitAudit 同约定)。单批一条,Details 记名单与
|
||||||
|
// 统计,供审计侧对账。
|
||||||
|
func (s *orgCenterService) emitAdoptAudit(ctx context.Context, tenantID uint64, adopted int, skipped []*types.OrgAdoptSkip) {
|
||||||
|
if s.audit == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ids := make([]string, 0, len(skipped))
|
||||||
|
for _, sk := range skipped {
|
||||||
|
ids = append(ids, sk.UserID)
|
||||||
|
}
|
||||||
|
details, err := json.Marshal(map[string]any{
|
||||||
|
"user_ids": ids,
|
||||||
|
"adopted": adopted,
|
||||||
|
"skipped": len(skipped),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor, _ := types.UserIDFromContext(ctx)
|
||||||
|
_ = s.audit.Log(ctx, &types.AuditLog{
|
||||||
|
TenantID: tenantID,
|
||||||
|
ActorUserID: actor,
|
||||||
|
ActorRole: string(types.TenantRoleFromContext(ctx)),
|
||||||
|
Action: types.AuditActionMemberHomeAdopted,
|
||||||
|
TargetType: "tenant_member",
|
||||||
|
Outcome: types.AuditOutcomeSuccess,
|
||||||
|
Details: details,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 模块角色绑定
|
// 模块角色绑定
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"academy/internal/types"
|
||||||
|
"academy/internal/types/interfaces"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 收编归属空间(AdoptHomeTenant):把成员的登录默认落点(users.tenant_id +
|
||||||
|
// 最近活跃租户偏好)批量改指本空间。场景回归:员工首登开了个人空间后,登录
|
||||||
|
// 落在个人空间,看不到本空间维护的组织架构;收编只动归属指针,成员关系与
|
||||||
|
// 个人空间数据不变。
|
||||||
|
|
||||||
|
// fakeAdoptOrgRepo 组织中心仓库桩:入册补建(EnsureEmployeesForUsers)路径。
|
||||||
|
type fakeAdoptOrgRepo struct {
|
||||||
|
interfaces.OrgCenterRepository
|
||||||
|
roster []*types.OrgEmployee // InsertEmployeesIfAbsent 收到的补建行
|
||||||
|
userInfos []*types.TrainingUserInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptOrgRepo) ListDepts(context.Context, uint64) ([]*types.OrgDept, error) {
|
||||||
|
return []*types.OrgDept{{ID: "d1", Name: "生产一部", Code: "D01"}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptOrgRepo) GetRosterUserInfos(_ context.Context, _ uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
|
||||||
|
byID := map[string]*types.TrainingUserInfo{}
|
||||||
|
for _, u := range f.userInfos {
|
||||||
|
byID[u.ID] = u
|
||||||
|
}
|
||||||
|
out := make([]*types.TrainingUserInfo, 0, len(userIDs))
|
||||||
|
for _, id := range userIDs {
|
||||||
|
if u, ok := byID[id]; ok {
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptOrgRepo) InsertEmployeesIfAbsent(_ context.Context, employees []*types.OrgEmployee) error {
|
||||||
|
f.roster = append(f.roster, employees...)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeAdoptUserRepo 用户仓库桩:收编读改写 users.tenant_id / 偏好。
|
||||||
|
type fakeAdoptUserRepo struct {
|
||||||
|
interfaces.UserRepository
|
||||||
|
users map[string]*types.User
|
||||||
|
updated []*types.User
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptUserRepo) GetUserByID(_ context.Context, id string) (*types.User, error) {
|
||||||
|
if u, ok := f.users[id]; ok {
|
||||||
|
return u, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptUserRepo) UpdateUser(_ context.Context, u *types.User) error {
|
||||||
|
f.updated = append(f.updated, u)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeAdoptMemberRepo 成员仓库桩:收编前校验目标空间活跃成员关系。
|
||||||
|
type fakeAdoptMemberRepo struct {
|
||||||
|
interfaces.TenantMemberRepository
|
||||||
|
members map[string]*types.TenantMember // key: user_id(目标空间)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAdoptMemberRepo) Get(_ context.Context, userID string, _ uint64) (*types.TenantMember, error) {
|
||||||
|
if m, ok := f.members[userID]; ok {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAdoptService(org *fakeAdoptOrgRepo, users *fakeAdoptUserRepo, members *fakeAdoptMemberRepo) interfaces.OrgCenterService {
|
||||||
|
return NewOrgCenterService(org, users, members, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdoptHomeTenantMovesHomeAndPreference(t *testing.T) {
|
||||||
|
org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{
|
||||||
|
{ID: "u-sun", Username: "26080007", DeptCode: "D01", DeptName: "生产一部"},
|
||||||
|
}}
|
||||||
|
pref := uint64(9) // 旧偏好指向个人空间:收编必须一并改指,否则登录仍落旧空间
|
||||||
|
users := &fakeAdoptUserRepo{users: map[string]*types.User{
|
||||||
|
"u-sun": {ID: "u-sun", Username: "26080007", IsActive: true, TenantID: 9,
|
||||||
|
Preferences: types.UserPreferences{LastActiveTenantID: &pref}},
|
||||||
|
}}
|
||||||
|
members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{
|
||||||
|
"u-sun": {UserID: "u-sun", TenantID: 2, Status: types.TenantMemberStatusActive},
|
||||||
|
}}
|
||||||
|
svc := newAdoptService(org, users, members)
|
||||||
|
|
||||||
|
result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{"u-sun"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("AdoptHomeTenant: %v", err)
|
||||||
|
}
|
||||||
|
if result.Adopted != 1 || len(result.Skipped) != 0 {
|
||||||
|
t.Fatalf("unexpected result: adopted=%d skipped=%+v", result.Adopted, result.Skipped)
|
||||||
|
}
|
||||||
|
saved := users.updated[0]
|
||||||
|
if saved.TenantID != 2 {
|
||||||
|
t.Fatalf("home tenant not moved: %d", saved.TenantID)
|
||||||
|
}
|
||||||
|
if saved.Preferences.LastActiveTenantID == nil || *saved.Preferences.LastActiveTenantID != 2 {
|
||||||
|
t.Fatalf("LastActiveTenantID not pointed at target: %+v", saved.Preferences.LastActiveTenantID)
|
||||||
|
}
|
||||||
|
// 收编成功者补跑自动入册:名册补建且部门按 dept_code 匹配。
|
||||||
|
if len(org.roster) != 1 || org.roster[0].UserID != "u-sun" || org.roster[0].DeptID != "d1" {
|
||||||
|
t.Fatalf("roster backfill missing or dept unmatched: %+v", org.roster)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdoptHomeTenantSkipsNonMembersAndSuperusers(t *testing.T) {
|
||||||
|
org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{
|
||||||
|
{ID: "u-in", Username: "26080007"},
|
||||||
|
}}
|
||||||
|
users := &fakeAdoptUserRepo{users: map[string]*types.User{
|
||||||
|
"u-in": {ID: "u-in", Username: "26080007", IsActive: true, TenantID: 9},
|
||||||
|
"u-super": {ID: "u-super", Username: "admin", IsActive: true, CanAccessAllTenants: true},
|
||||||
|
"u-out": {ID: "u-out", Username: "26010001", IsActive: true, TenantID: 9},
|
||||||
|
"u-off": {ID: "u-off", Username: "26010002", IsActive: false, TenantID: 9},
|
||||||
|
"u-home": {ID: "u-home", Username: "26010003", IsActive: true, TenantID: 2},
|
||||||
|
// u-ghost 不在用户表(账号已消失),收编按「平台账号不存在」跳过。
|
||||||
|
}}
|
||||||
|
members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{
|
||||||
|
// u-in 是本空间活跃成员(唯一收编对象);u-super 是成员但跨空间账号
|
||||||
|
// 不自动收编;u-off 成员关系已停用。
|
||||||
|
"u-in": {UserID: "u-in", TenantID: 2, Status: types.TenantMemberStatusActive},
|
||||||
|
"u-super": {UserID: "u-super", TenantID: 2, Status: types.TenantMemberStatusActive},
|
||||||
|
"u-off": {UserID: "u-off", TenantID: 2, Status: types.TenantMemberStatusSuspended},
|
||||||
|
}}
|
||||||
|
svc := newAdoptService(org, users, members)
|
||||||
|
|
||||||
|
result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{
|
||||||
|
"u-in", "u-super", "u-out", "u-off", "u-home", "u-ghost",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("AdoptHomeTenant: %v", err)
|
||||||
|
}
|
||||||
|
if result.Adopted != 1 {
|
||||||
|
t.Fatalf("only u-in should be adopted, got %d (%+v)", result.Adopted, result.Skipped)
|
||||||
|
}
|
||||||
|
reasons := map[string]string{}
|
||||||
|
for _, sk := range result.Skipped {
|
||||||
|
reasons[sk.UserID] = sk.Reason
|
||||||
|
}
|
||||||
|
want := map[string]string{
|
||||||
|
"u-super": "跨空间账号不自动收编",
|
||||||
|
"u-out": "非本空间成员,请先邀请或批量导入加入",
|
||||||
|
// 停用账号在成员关系校验前拦截:账号不可用,收编无意义。
|
||||||
|
"u-off": "账号已停用",
|
||||||
|
"u-home": "归属空间已是本空间",
|
||||||
|
"u-ghost": "平台账号不存在",
|
||||||
|
}
|
||||||
|
for id, reason := range want {
|
||||||
|
if reasons[id] != reason {
|
||||||
|
t.Fatalf("user %s reason = %q, want %q", id, reasons[id], reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 仅收编成功者(u-in)触发补建;跳过者不写任何用户行。
|
||||||
|
if len(org.roster) != 1 || org.roster[0].UserID != "u-in" {
|
||||||
|
t.Fatalf("roster backfill should only cover adopted users: %+v", org.roster)
|
||||||
|
}
|
||||||
|
if len(users.updated) != 1 || users.updated[0].ID != "u-in" {
|
||||||
|
t.Fatalf("only adopted user should be persisted: %+v", users.updated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdoptHomeTenantGuards(t *testing.T) {
|
||||||
|
svc := newAdoptService(&fakeAdoptOrgRepo{}, &fakeAdoptUserRepo{}, &fakeAdoptMemberRepo{})
|
||||||
|
if _, err := svc.AdoptHomeTenant(context.Background(), 0, []string{"u"}); err == nil {
|
||||||
|
t.Fatal("zero tenant must be rejected")
|
||||||
|
}
|
||||||
|
if _, err := svc.AdoptHomeTenant(context.Background(), 2, nil); err == nil {
|
||||||
|
t.Fatal("empty user list must be rejected")
|
||||||
|
}
|
||||||
|
// 依赖未装配(users/members 为 nil)时报错而不是 panic。
|
||||||
|
noDep := NewOrgCenterService(&fakeAdoptOrgRepo{}, nil, nil, nil)
|
||||||
|
if _, err := noDep.AdoptHomeTenant(context.Background(), 2, []string{"u"}); err == nil {
|
||||||
|
t.Fatal("missing deps must error, not panic")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,7 +52,7 @@ func newFakeOrgRepo() *fakeOrgRepo {
|
|||||||
|
|
||||||
func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
|
func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
|
||||||
repo := newFakeOrgRepo()
|
repo := newFakeOrgRepo()
|
||||||
svc := NewOrgCenterService(repo)
|
svc := NewOrgCenterService(repo, nil, nil, nil)
|
||||||
employees := []*types.OrgEmployee{
|
employees := []*types.OrgEmployee{
|
||||||
{UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号
|
{UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号
|
||||||
{UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号
|
{UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号
|
||||||
@@ -76,7 +76,7 @@ func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) {
|
|||||||
|
|
||||||
func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) {
|
func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) {
|
||||||
repo := newFakeOrgRepo()
|
repo := newFakeOrgRepo()
|
||||||
svc := NewOrgCenterService(repo)
|
svc := NewOrgCenterService(repo, nil, nil, nil)
|
||||||
// u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。
|
// u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。
|
||||||
employees := []*types.OrgEmployee{
|
employees := []*types.OrgEmployee{
|
||||||
{UserID: "u-qu", DeptID: "d1"},
|
{UserID: "u-qu", DeptID: "d1"},
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"academy/internal/logger"
|
"academy/internal/logger"
|
||||||
"academy/internal/types"
|
"academy/internal/types"
|
||||||
@@ -20,7 +21,9 @@ import (
|
|||||||
// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先);
|
// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先);
|
||||||
// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型;
|
// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型;
|
||||||
// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化);
|
// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化);
|
||||||
// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认。
|
// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认;
|
||||||
|
// 5. 确保企业培训「课件/题库」两个系统默认知识库(CASDOOR/OIDC 自动注册
|
||||||
|
// 用户进「知识库」页默认可见,与培训域共用同一对库)。
|
||||||
//
|
//
|
||||||
// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程;
|
// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程;
|
||||||
// 且整体幂等——租户下已存在同名入门库时直接跳过。
|
// 且整体幂等——租户下已存在同名入门库时直接跳过。
|
||||||
@@ -87,6 +90,8 @@ type tenantBootstrapService struct {
|
|||||||
kbService interfaces.KnowledgeBaseService
|
kbService interfaces.KnowledgeBaseService
|
||||||
kgService interfaces.KnowledgeService
|
kgService interfaces.KnowledgeService
|
||||||
tenantService interfaces.TenantService
|
tenantService interfaces.TenantService
|
||||||
|
// ensureMu 串行化惰性自愈的补建段(见 EnsureTenantDefaultKnowledgeBases)。
|
||||||
|
ensureMu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the
|
// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the
|
||||||
@@ -103,7 +108,11 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
|
|||||||
if tenant == nil || tenant.ID == 0 {
|
if tenant == nil || tenant.ID == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。
|
// 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。000160 起
|
||||||
|
// 租户序列已避开 10000(见 migration 000160_tenant_seq_reserve_builtin_host),
|
||||||
|
// 新环境不会再有真实空间拿到该 id;存量环境若首空间已占住 10000(引导因此
|
||||||
|
// 被跳过,一个默认库都没有),其默认库由 EnsureTenantDefaultKnowledgeBases
|
||||||
|
// 惰性自愈补齐——该路径不带本豁免。
|
||||||
if tenant.ID == types.DefaultBuiltinModelTenantID {
|
if tenant.ID == types.DefaultBuiltinModelTenantID {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -124,6 +133,12 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
|
|||||||
logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 企业培训(课件)/(题库)系统默认库:按 Source 标记独立幂等确保(与培训域
|
||||||
|
// ensureTrainingKnowledgeBases 同源),入门库已初始化的空间同样补齐 ——
|
||||||
|
// CASDOOR/OIDC 自动注册的用户进「知识库」页即可见两个培训默认库。
|
||||||
|
s.ensureTrainingKnowledgeBases(seedCtx, tenant.ID, kbs)
|
||||||
|
|
||||||
for _, kb := range kbs {
|
for _, kb := range kbs {
|
||||||
if kb != nil && kb.Name == BootstrapKBName {
|
if kb != nil && kb.Name == BootstrapKBName {
|
||||||
logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID)
|
logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID)
|
||||||
@@ -141,32 +156,13 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
|
|||||||
embedID := PickDefaultModelID(models, types.ModelTypeEmbedding)
|
embedID := PickDefaultModelID(models, types.ModelTypeEmbedding)
|
||||||
rerankID := PickDefaultModelID(models, types.ModelTypeRerank)
|
rerankID := PickDefaultModelID(models, types.ModelTypeRerank)
|
||||||
|
|
||||||
// 1) 默认知识库。模型解析不到就留空——行为与用户手动不选一致。
|
// 1) 默认知识库 + 欢迎文档(创建时引导与存量空间自愈共用同一实现)。
|
||||||
kb := &types.KnowledgeBase{
|
// 模型解析不到就留空——行为与用户手动不选一致。
|
||||||
Name: BootstrapKBName,
|
if err := s.seedStarterKB(seedCtx, chatID, embedID); err != nil {
|
||||||
Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。",
|
|
||||||
Type: types.KnowledgeBaseTypeDocument,
|
|
||||||
SummaryModelID: chatID,
|
|
||||||
EmbeddingModelID: embedID,
|
|
||||||
}
|
|
||||||
createdKB, err := s.kbService.CreateKnowledgeBase(seedCtx, kb)
|
|
||||||
if err != nil {
|
|
||||||
logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: tenant=%d err=%v", tenant.ID, err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
logger.Infof(ctx, "tenant bootstrap: starter KB created: tenant=%d kb=%s", tenant.ID, createdKB.ID)
|
|
||||||
|
|
||||||
// 2) 预置欢迎文档(标准上传管道,切片/向量化由后台任务异步完成)。
|
// 2) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
|
||||||
if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil {
|
|
||||||
logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: tenant=%d err=%v", tenant.ID, fhErr)
|
|
||||||
} else if _, upErr := s.kgService.CreateKnowledgeFromFile(seedCtx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil {
|
|
||||||
logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: tenant=%d kb=%s err=%v",
|
|
||||||
tenant.ID, createdKB.ID, upErr)
|
|
||||||
} else {
|
|
||||||
logger.Infof(ctx, "tenant bootstrap: welcome doc queued: tenant=%d kb=%s", tenant.ID, createdKB.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
|
|
||||||
if rerankID != "" {
|
if rerankID != "" {
|
||||||
if tenant.RetrievalConfig == nil {
|
if tenant.RetrievalConfig == nil {
|
||||||
tenant.RetrievalConfig = &types.RetrievalConfig{}
|
tenant.RetrievalConfig = &types.RetrievalConfig{}
|
||||||
@@ -184,6 +180,168 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seedStarterKB 创建「新手入门」知识库并预置欢迎文档(标准上传管道,切片/
|
||||||
|
// 向量化由后台任务异步完成)。创建时引导(SeedTenantDefaults)与存量空间
|
||||||
|
// 惰性自愈(EnsureTenantDefaultKnowledgeBases)共用同一实现。fail-open:
|
||||||
|
// 失败仅记日志返回 error,由调用方决定是否中断后续步骤。
|
||||||
|
func (s *tenantBootstrapService) seedStarterKB(ctx context.Context, chatID, embedID string) error {
|
||||||
|
kb := &types.KnowledgeBase{
|
||||||
|
Name: BootstrapKBName,
|
||||||
|
Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。",
|
||||||
|
Type: types.KnowledgeBaseTypeDocument,
|
||||||
|
SummaryModelID: chatID,
|
||||||
|
EmbeddingModelID: embedID,
|
||||||
|
}
|
||||||
|
createdKB, err := s.kbService.CreateKnowledgeBase(ctx, kb)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: err=%v", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "tenant bootstrap: starter KB created: kb=%s", createdKB.ID)
|
||||||
|
|
||||||
|
if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: kb=%s err=%v", createdKB.ID, fhErr)
|
||||||
|
} else if _, upErr := s.kgService.CreateKnowledgeFromFile(ctx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: kb=%s err=%v", createdKB.ID, upErr)
|
||||||
|
} else {
|
||||||
|
logger.Infof(ctx, "tenant bootstrap: welcome doc queued: kb=%s", createdKB.ID)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureTenantDefaultKnowledgeBases implements interfaces.TenantBootstrapService.
|
||||||
|
// 存量空间默认库惰性自愈:注册/建空间引导是一次性动作,历史空间会因引导
|
||||||
|
// 当时的失败(如模型尚未就绪)或保留租户 id 碰撞(migration 000160 前首空间
|
||||||
|
// 占住 10000 被豁免)而缺失默认库。知识库列表访问时幂等补齐:
|
||||||
|
// - 企业培训「课件/题库」两库恒补(Source 标记去重);
|
||||||
|
// - 「新手入门」仅空间为空时补建——零库说明引导从未成功;用户已在使用的
|
||||||
|
// 空间不复活其主动删除的入门库。
|
||||||
|
//
|
||||||
|
// 必须幂等且 fail-open:挂在列表读路径上,任何失败只记日志,不影响正常返回。
|
||||||
|
func (s *tenantBootstrapService) EnsureTenantDefaultKnowledgeBases(ctx context.Context) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
logger.Errorf(ctx, "tenant bootstrap: lazy ensure recovered from panic: %v", r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||||
|
if !ok || tenantID == 0 || s.kbService == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 快路径:三项默认库齐备直接返回(一次只读列表,绝大多数请求止于此)。
|
||||||
|
kbs, err := s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tenantDefaultsComplete(kbs) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 进程内串行化:并发的列表请求只允许一个进入补建段,防止同名默认库
|
||||||
|
// 重复建档(CreateKnowledgeBase 无名称唯一约束)。锁内复查双保险。
|
||||||
|
s.ensureMu.Lock()
|
||||||
|
defer s.ensureMu.Unlock()
|
||||||
|
kbs, err = s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tenantDefaultsComplete(kbs) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自愈上下文:执行租户落到目标空间;补建人取当前登录用户(与引导同口径,
|
||||||
|
// 合成 API-key 用户跳过);CreateKnowledgeFromFile 依赖 TenantInfo。
|
||||||
|
seedCtx := types.WithExecutionTenant(ctx, tenantID)
|
||||||
|
if tenant, tErr := s.tenantService.GetTenantByID(ctx, tenantID); tErr == nil && tenant != nil {
|
||||||
|
seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant)
|
||||||
|
}
|
||||||
|
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
|
||||||
|
seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, uid)
|
||||||
|
}
|
||||||
|
logger.Infof(seedCtx, "tenant bootstrap: lazy ensure defaults, tenant=%d existing_kbs=%d", tenantID, len(kbs))
|
||||||
|
|
||||||
|
// 培训两库恒补;「新手入门」仅零库空间补建(见方法注释)。
|
||||||
|
s.ensureTrainingKnowledgeBases(seedCtx, tenantID, kbs)
|
||||||
|
if len(kbs) == 0 {
|
||||||
|
models, mErr := s.modelService.ListModels(seedCtx)
|
||||||
|
if mErr != nil {
|
||||||
|
logger.Warnf(seedCtx, "tenant bootstrap: lazy ensure list models failed: tenant=%d err=%v", tenantID, mErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = s.seedStarterKB(seedCtx,
|
||||||
|
PickDefaultModelID(models, types.ModelTypeKnowledgeQA),
|
||||||
|
PickDefaultModelID(models, types.ModelTypeEmbedding))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tenantDefaultsComplete 判断空间的开箱默认库是否齐备:新手入门 + 培训课件 +
|
||||||
|
// 培训题库三项都在才算完整。
|
||||||
|
func tenantDefaultsComplete(kbs []*types.KnowledgeBase) bool {
|
||||||
|
var hasStarter, hasCourseware, hasBank bool
|
||||||
|
for _, kb := range kbs {
|
||||||
|
if kb == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case kb.Name == BootstrapKBName:
|
||||||
|
hasStarter = true
|
||||||
|
case kb.Source == types.KnowledgeBaseSourceTrainingCourseware:
|
||||||
|
hasCourseware = true
|
||||||
|
case kb.Source == types.KnowledgeBaseSourceTrainingQuestionBank:
|
||||||
|
hasBank = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasStarter && hasCourseware && hasBank
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureTrainingKnowledgeBases 确保「企业培训(课件)/(题库)」两个系统默认库
|
||||||
|
// 存在(按 Source 标记去重,缺失即建,已存在跳过;模型由 CreateKnowledgeBase
|
||||||
|
// 的默认兜底自动绑定)。与培训域 trainingService.ensureTrainingKnowledgeBases
|
||||||
|
// 完全同源:后续培训上传/题库导入按同一 Source 标记复用这里的库,不会重复建档。
|
||||||
|
// fail-open:单库失败仅记日志,不阻断注册/建租户主流程。
|
||||||
|
func (s *tenantBootstrapService) ensureTrainingKnowledgeBases(ctx context.Context, tenantID uint64, existing []*types.KnowledgeBase) {
|
||||||
|
if s.kbService == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hasSource := func(source string) bool {
|
||||||
|
for _, kb := range existing {
|
||||||
|
if kb != nil && kb.Source == source {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seeds := []struct {
|
||||||
|
source string
|
||||||
|
name string
|
||||||
|
description string
|
||||||
|
}{
|
||||||
|
{types.KnowledgeBaseSourceTrainingCourseware, trainingCoursewareKBName, trainingCoursewareKBDescription},
|
||||||
|
{types.KnowledgeBaseSourceTrainingQuestionBank, trainingQuestionBankKBName, trainingQuestionBankKBDescription},
|
||||||
|
}
|
||||||
|
for _, seed := range seeds {
|
||||||
|
if hasSource(seed.source) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
created, err := s.kbService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
|
||||||
|
Name: seed.name,
|
||||||
|
Description: seed.description,
|
||||||
|
Source: seed.source,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "tenant bootstrap: ensure training KB failed: tenant=%d source=%s err=%v",
|
||||||
|
tenantID, seed.source, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "tenant bootstrap: training KB ensured: tenant=%d kb=%s source=%s",
|
||||||
|
tenantID, created.ID, seed.source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// PickDefaultModelID returns the tenant-visible default model of the given
|
// PickDefaultModelID returns the tenant-visible default model of the given
|
||||||
// type: the is_default row first, then the first active row. Empty string
|
// type: the is_default row first, then the first active row. Empty string
|
||||||
// when the deployment has no usable model of that type. Shared by the
|
// when the deployment has no usable model of that type. Shared by the
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ type tenantMemberService struct {
|
|||||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||||
userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers
|
userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers
|
||||||
tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal
|
tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal
|
||||||
|
org interfaces.OrgCenterService // optional; 成员加入时自动入册组织架构(见 ensureOrgRoster)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTenantMemberService constructs the service. Wired up via the DI
|
// NewTenantMemberService constructs the service. Wired up via the DI
|
||||||
@@ -100,12 +101,28 @@ func NewTenantMemberService(
|
|||||||
audit interfaces.AuditLogService,
|
audit interfaces.AuditLogService,
|
||||||
userRepo interfaces.UserRepository,
|
userRepo interfaces.UserRepository,
|
||||||
tokenRepo interfaces.AuthTokenRepository,
|
tokenRepo interfaces.AuthTokenRepository,
|
||||||
|
org interfaces.OrgCenterService,
|
||||||
) interfaces.TenantMemberService {
|
) interfaces.TenantMemberService {
|
||||||
return &tenantMemberService{
|
return &tenantMemberService{
|
||||||
repo: repo,
|
repo: repo,
|
||||||
audit: audit,
|
audit: audit,
|
||||||
userRepo: userRepo,
|
userRepo: userRepo,
|
||||||
tokenRepo: tokenRepo,
|
tokenRepo: tokenRepo,
|
||||||
|
org: org,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureOrgRoster 成员加入空间后自动补建组织架构员工档案(fail-open)。
|
||||||
|
// 需求:平台新增成员自动添加到「组织架构」并按同步部门(dept_code/dept_name)
|
||||||
|
// 自动匹配;对已是成员的用户同样触发(存量自愈),重复调用由
|
||||||
|
// InsertEmployeesIfAbsent 的仅补空 upsert 幂等兜底,人工维护字段不受影响。
|
||||||
|
func (s *tenantMemberService) ensureOrgRoster(ctx context.Context, userID string, tenantID uint64) {
|
||||||
|
if s.org == nil || userID == "" || tenantID == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.org.EnsureEmployeesForUsers(ctx, tenantID, []string{userID}); err != nil {
|
||||||
|
logger.Warnf(ctx, "[OrgCenter] auto-roster failed (member join continues): user=%s tenant=%d err=%v",
|
||||||
|
userID, tenantID, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,6 +188,8 @@ func (s *tenantMemberService) AddMember(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if existing != nil {
|
if existing != nil {
|
||||||
|
// 已是成员:仍补一次入册(存量成员档案缺失时的自愈口)。
|
||||||
|
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||||
return nil, ErrMembershipAlreadyExists
|
return nil, ErrMembershipAlreadyExists
|
||||||
}
|
}
|
||||||
member := &types.TenantMember{
|
member := &types.TenantMember{
|
||||||
@@ -201,6 +220,8 @@ func (s *tenantMemberService) AddMember(
|
|||||||
TargetUserID: userID,
|
TargetUserID: userID,
|
||||||
Outcome: types.AuditOutcomeSuccess,
|
Outcome: types.AuditOutcomeSuccess,
|
||||||
})
|
})
|
||||||
|
// 成员关系落库后自动入册组织架构(新增成员自动添加到名册并匹配部门)。
|
||||||
|
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||||
return member, nil
|
return member, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,6 +239,7 @@ func (s *tenantMemberService) EnsureOwner(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if existing != nil {
|
if existing != nil {
|
||||||
|
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||||
return existing, nil
|
return existing, nil
|
||||||
}
|
}
|
||||||
member := &types.TenantMember{
|
member := &types.TenantMember{
|
||||||
@@ -239,12 +261,15 @@ func (s *tenantMemberService) EnsureOwner(
|
|||||||
logger.Infof(ctx,
|
logger.Infof(ctx,
|
||||||
"EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)",
|
"EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)",
|
||||||
userID, tenantID, winner.Role)
|
userID, tenantID, winner.Role)
|
||||||
|
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||||
return winner, nil
|
return winner, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID)
|
logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID)
|
||||||
|
// 注册建空间的 Owner 同样自动入册(个人空间名册含创建者本人)。
|
||||||
|
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||||
return member, nil
|
return member, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -215,7 +215,7 @@ func newSyncService(
|
|||||||
AdminOrganization: "built-in",
|
AdminOrganization: "built-in",
|
||||||
EmailFallbackDomain: "casdoor.local",
|
EmailFallbackDomain: "casdoor.local",
|
||||||
}}
|
}}
|
||||||
orgSvc := NewOrgCenterService(orgRepo)
|
orgSvc := NewOrgCenterService(orgRepo, nil, nil, nil)
|
||||||
return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc)
|
return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,7 +401,7 @@ func TestSyncCasdoorGrantNotSupported(t *testing.T) {
|
|||||||
AdminOrganization: "built-in",
|
AdminOrganization: "built-in",
|
||||||
}}
|
}}
|
||||||
// ClientID 为空 → client.Enabled() 为 false → 配置提示路径。
|
// ClientID 为空 → client.Enabled() 为 false → 配置提示路径。
|
||||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo))
|
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||||
_, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
_, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||||
if err == nil || !strings.Contains(err.Error(), "未启用") {
|
if err == nil || !strings.Contains(err.Error(), "未启用") {
|
||||||
t.Fatalf("disabled config should surface actionable error, got: %v", err)
|
t.Fatalf("disabled config should surface actionable error, got: %v", err)
|
||||||
@@ -431,7 +431,7 @@ func TestSyncCasdoorPasswordMode(t *testing.T) {
|
|||||||
AdminPassword: "secret-pwd",
|
AdminPassword: "secret-pwd",
|
||||||
EmailFallbackDomain: "casdoor.local",
|
EmailFallbackDomain: "casdoor.local",
|
||||||
}}
|
}}
|
||||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo))
|
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||||
|
|
||||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -465,7 +465,7 @@ func TestSyncCasdoorWrappedPayload(t *testing.T) {
|
|||||||
AdminPassword: "secret-pwd",
|
AdminPassword: "secret-pwd",
|
||||||
EmailFallbackDomain: "casdoor.local",
|
EmailFallbackDomain: "casdoor.local",
|
||||||
}}
|
}}
|
||||||
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo))
|
svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil))
|
||||||
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
res, err := svc.SyncMembers(context.Background(), 7, "op-1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("SyncMembers(wrapped): %v", err)
|
t.Fatalf("SyncMembers(wrapped): %v", err)
|
||||||
|
|||||||
@@ -272,7 +272,7 @@ func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo
|
|||||||
// tests pre-date PR 6 and exercise membership invariants only. The
|
// tests pre-date PR 6 and exercise membership invariants only. The
|
||||||
// service's audit and RemoveMember-cleanup hooks are nil-safe, so
|
// service's audit and RemoveMember-cleanup hooks are nil-safe, so
|
||||||
// passing nil keeps existing coverage intact without forcing stubs.
|
// passing nil keeps existing coverage intact without forcing stubs.
|
||||||
return NewTenantMemberService(r, nil, nil, nil), r
|
return NewTenantMemberService(r, nil, nil, nil, nil), r
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanupUserRepo is a minimal UserRepository used to assert that
|
// cleanupUserRepo is a minimal UserRepository used to assert that
|
||||||
@@ -359,7 +359,7 @@ func TestTenantMemberService_RemoveMember_ClearsStaleHomeAndRevokesTokens(t *tes
|
|||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
tokenRepo := &cleanupTokenRepo{}
|
tokenRepo := &cleanupTokenRepo{}
|
||||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||||
@@ -396,7 +396,7 @@ func TestTenantMemberService_RemoveMember_RevokesTokensEvenWhenHomeUnchanged(t *
|
|||||||
"contrib": {ID: "contrib", TenantID: 1},
|
"contrib": {ID: "contrib", TenantID: 1},
|
||||||
}}
|
}}
|
||||||
tokenRepo := &cleanupTokenRepo{}
|
tokenRepo := &cleanupTokenRepo{}
|
||||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||||
|
|||||||
@@ -291,6 +291,25 @@ func (s *trainingService) CurrentMember(ctx context.Context, tenantID uint64, us
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResolveTrainingTenant 企业培训数据空间解析(000160):培训域不再绑定单一工作区
|
||||||
|
// —— 同一组织的人员只要员工档案(org_employees)里存在,无论当前在哪个工作区,
|
||||||
|
// 都按其档案所在空间参与培训、课程发布与学习。优先级:
|
||||||
|
// 1. 当前空间已有培训档案 → 当前空间(多档案用户显式切换工作区的语义优先);
|
||||||
|
// 2. 否则跨空间取最早在职档案所在空间;
|
||||||
|
// 3. 都没有 → 维持当前空间(默认学员口径,行为与升级前一致)。
|
||||||
|
func (s *trainingService) ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error) {
|
||||||
|
if userID == "" || activeTenantID == 0 {
|
||||||
|
return activeTenantID, nil
|
||||||
|
}
|
||||||
|
if _, err := s.repo.GetMemberByUserID(ctx, activeTenantID, userID); err == nil {
|
||||||
|
return activeTenantID, nil
|
||||||
|
}
|
||||||
|
if tenantID, err := s.repo.FindArchiveTenantID(ctx, userID); err == nil && tenantID != 0 {
|
||||||
|
return tenantID, nil
|
||||||
|
}
|
||||||
|
return activeTenantID, nil
|
||||||
|
}
|
||||||
|
|
||||||
// trainingMemberWithRoles 填充员工档案的培训模块绑定角色展示字段。
|
// trainingMemberWithRoles 填充员工档案的培训模块绑定角色展示字段。
|
||||||
func (s *trainingService) trainingMemberWithRoles(ctx context.Context, tenantID uint64, member *types.TrainingMember) (*types.TrainingMember, error) {
|
func (s *trainingService) trainingMemberWithRoles(ctx context.Context, tenantID uint64, member *types.TrainingMember) (*types.TrainingMember, error) {
|
||||||
binding, err := s.org.GetModuleMember(ctx, tenantID, types.OrgModuleTraining, member.ID)
|
binding, err := s.org.GetModuleMember(ctx, tenantID, types.OrgModuleTraining, member.ID)
|
||||||
@@ -372,6 +391,8 @@ func (s *trainingService) EnsureLecturerRole(ctx context.Context, tenantID uint6
|
|||||||
// SaveDemand creates or updates one demand with rule-based field checking.
|
// SaveDemand creates or updates one demand with rule-based field checking.
|
||||||
// 已确认的需求不再允许编辑(先由人事回退)。
|
// 已确认的需求不再允许编辑(先由人事回退)。
|
||||||
func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) {
|
func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) {
|
||||||
|
// 编辑场景的存量值(课程关联保留口径,见下方课程校验)。
|
||||||
|
var prevLibraryCourseID, prevCourseName string
|
||||||
if demand.CourseName == "" {
|
if demand.CourseName == "" {
|
||||||
return nil, errors.NewBadRequestError("课程名称不能为空")
|
return nil, errors.NewBadRequestError("课程名称不能为空")
|
||||||
}
|
}
|
||||||
@@ -393,6 +414,10 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
|||||||
if existing.Status == types.TrainingDemandConfirmed {
|
if existing.Status == types.TrainingDemandConfirmed {
|
||||||
return nil, errors.NewBadRequestError("已确认的需求不可编辑")
|
return nil, errors.NewBadRequestError("已确认的需求不可编辑")
|
||||||
}
|
}
|
||||||
|
// 编辑保留原课程关联(000158):课程名未变时跳过重匹配,匹配失败时不
|
||||||
|
// 清空已有关联(UpdateDemand 全量更新,零值会误清)。
|
||||||
|
prevLibraryCourseID = existing.LibraryCourseID
|
||||||
|
prevCourseName = existing.CourseName
|
||||||
}
|
}
|
||||||
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
|
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
|
||||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||||
@@ -413,6 +438,33 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
|||||||
demand.Status = types.TrainingDemandSubmitted
|
demand.Status = types.TrainingDemandSubmitted
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 课程校验(000158):按课程名称在课程管理精准查找,命中自动匹配该课程;
|
||||||
|
// 未命中自动新增该课程(待核验,归属需求部门)。匹配/建档失败为硬失败:
|
||||||
|
// 整个保存随之中止并向前端透出原因(不静默跳过,避免"需求存了但课程没建"
|
||||||
|
// 的隐性不一致)。课程名未变且已有关联时跳过重匹配(编辑保留原关联)。
|
||||||
|
// 外部讲师口径已在上方互斥清空,这里原样透传即可。
|
||||||
|
switch {
|
||||||
|
case prevLibraryCourseID != "" && prevCourseName == demand.CourseName:
|
||||||
|
demand.LibraryCourseID = prevLibraryCourseID
|
||||||
|
case strings.TrimSpace(demand.CourseName) != "":
|
||||||
|
proto := &types.TrainingCourseLibrary{
|
||||||
|
Name: demand.CourseName,
|
||||||
|
OwnerDeptID: demand.DeptID,
|
||||||
|
Category: demand.Category,
|
||||||
|
SuitableMembers: demand.PostScope,
|
||||||
|
LecturerID: demand.LecturerID,
|
||||||
|
LecturerExternal: demand.LecturerExternal,
|
||||||
|
}
|
||||||
|
id, _, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, demand.SubmitterID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, demand.CourseName, err)
|
||||||
|
return nil, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
|
||||||
|
}
|
||||||
|
demand.LibraryCourseID = id
|
||||||
|
default:
|
||||||
|
demand.LibraryCourseID = prevLibraryCourseID
|
||||||
|
}
|
||||||
|
|
||||||
if demand.ID == "" {
|
if demand.ID == "" {
|
||||||
demand.ID = trainingNewID()
|
demand.ID = trainingNewID()
|
||||||
demand.TenantID = tenantID
|
demand.TenantID = tenantID
|
||||||
@@ -431,10 +483,14 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ImportDemands batch-imports demands (调研表在线化/邮件替代)。
|
// ImportDemands batch-imports demands (调研表在线化/邮件替代)。
|
||||||
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error) {
|
// 返回导入行与自动新增的待核验课程数(000158)。
|
||||||
|
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error) {
|
||||||
if len(demands) == 0 {
|
if len(demands) == 0 {
|
||||||
return nil, errors.NewBadRequestError("导入数据为空")
|
return nil, 0, errors.NewBadRequestError("导入数据为空")
|
||||||
}
|
}
|
||||||
|
// 课程校验批内去重(000158):同名行只查/建一次,其余行复用条目 id。
|
||||||
|
courseCache := map[string]string{}
|
||||||
|
coursesCreated := 0
|
||||||
for i := range demands {
|
for i := range demands {
|
||||||
demands[i].ID = trainingNewID()
|
demands[i].ID = trainingNewID()
|
||||||
demands[i].TenantID = tenantID
|
demands[i].TenantID = tenantID
|
||||||
@@ -450,17 +506,51 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
|
|||||||
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
|
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
|
||||||
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
||||||
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
|
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
|
||||||
|
// 讲师口径互斥与 SaveDemand 一致:系统员工优先,外部姓名仅在无 id 时生效。
|
||||||
|
if demands[i].LecturerID != "" {
|
||||||
|
demands[i].LecturerExternal = ""
|
||||||
|
}
|
||||||
msgs := []string{}
|
msgs := []string{}
|
||||||
if demands[i].DeptID == "" {
|
if demands[i].DeptID == "" {
|
||||||
msgs = append(msgs, "未指定部门")
|
msgs = append(msgs, "未指定部门")
|
||||||
}
|
}
|
||||||
demands[i].CheckMsg = strings.Join(msgs, ";")
|
demands[i].CheckMsg = strings.Join(msgs, ";")
|
||||||
demands[i].CheckStatus = types.TrainingCheckPending
|
demands[i].CheckStatus = types.TrainingCheckPending
|
||||||
|
|
||||||
|
// 课程校验(000158):按名称精准查找自动匹配,未命中自动新增(待核验)。
|
||||||
|
// 硬失败同 SaveDemand:任一行匹配/建档失败整批中止并透出原因;
|
||||||
|
// 批内同名复用首个条目,不重复建档。
|
||||||
|
name := strings.TrimSpace(demands[i].CourseName)
|
||||||
|
if name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if id, ok := courseCache[name]; ok {
|
||||||
|
demands[i].LibraryCourseID = id
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
proto := &types.TrainingCourseLibrary{
|
||||||
|
Name: name,
|
||||||
|
OwnerDeptID: demands[i].DeptID,
|
||||||
|
Category: demands[i].Category,
|
||||||
|
SuitableMembers: demands[i].PostScope,
|
||||||
|
LecturerID: demands[i].LecturerID,
|
||||||
|
LecturerExternal: demands[i].LecturerExternal,
|
||||||
|
}
|
||||||
|
id, created, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, updaterID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, name, err)
|
||||||
|
return nil, 0, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
|
||||||
|
}
|
||||||
|
courseCache[name] = id
|
||||||
|
demands[i].LibraryCourseID = id
|
||||||
|
if created {
|
||||||
|
coursesCreated++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
|
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
|
||||||
return nil, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
return demands, nil
|
return demands, coursesCreated, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConfirmDemand marks one demand confirmed and auto-aggregates it into the
|
// ConfirmDemand marks one demand confirmed and auto-aggregates it into the
|
||||||
|
|||||||
@@ -130,9 +130,10 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
|
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
|
||||||
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/
|
// 课程名称/类型/形式随课程管理主数据锁定;讲师 000161 起计划侧可改(更新路径
|
||||||
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。
|
// 不再覆盖,改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时
|
||||||
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
|
// 讲师/学时/课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按
|
||||||
|
// 原值保存(fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
|
||||||
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
|
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
|
||||||
if course.LibraryCourseID == "" {
|
if course.LibraryCourseID == "" {
|
||||||
return nil
|
return nil
|
||||||
@@ -146,7 +147,8 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
|
|||||||
course.Name = item.Name
|
course.Name = item.Name
|
||||||
course.Type = item.Type
|
course.Type = item.Type
|
||||||
course.Mode = item.Mode
|
course.Mode = item.Mode
|
||||||
if item.LecturerID != "" || item.LecturerExternal != "" {
|
if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") {
|
||||||
|
// 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。
|
||||||
course.LecturerID = item.LecturerID
|
course.LecturerID = item.LecturerID
|
||||||
course.LecturerExternal = item.LecturerExternal
|
course.LecturerExternal = item.LecturerExternal
|
||||||
}
|
}
|
||||||
@@ -172,6 +174,35 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
|
|||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// syncPlanLecturerToLibrary 计划侧讲师改动回写课程管理主数据(000161):
|
||||||
|
// 讲师(系统员工 id/外部姓名)与课程管理条目不一致时经 SaveCourseLibraryItem
|
||||||
|
// 回写——其编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须由
|
||||||
|
// 所属部门课长/经理重新签核。fail-open:回写失败记日志不阻断计划保存。
|
||||||
|
func (s *trainingService) syncPlanLecturerToLibrary(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, course *types.TrainingCourse, updaterID string) {
|
||||||
|
if item == nil || course == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lecturerID, lecturerExt := strings.TrimSpace(course.LecturerID), strings.TrimSpace(course.LecturerExternal)
|
||||||
|
if lecturerID != "" {
|
||||||
|
lecturerExt = ""
|
||||||
|
}
|
||||||
|
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updated := *item
|
||||||
|
updated.LecturerID = lecturerID
|
||||||
|
updated.LecturerExternal = lecturerExt
|
||||||
|
if _, err := s.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
|
||||||
|
logger.Error(ctx, "Failed to sync plan lecturer to course library", err, "library_course_id", item.ID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "[Training] plan lecturer synced to library (verify reset), tenant=%d course=%s operator=%s", tenantID, item.Code, updaterID)
|
||||||
|
// 讲师自动补齐 lecturer 角色绑定(讲师名册/下拉可见,fail-open)。
|
||||||
|
if err := s.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
|
||||||
|
logger.Error(ctx, "Failed to ensure lecturer role on plan sync", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
|
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
|
||||||
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
|
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
|
||||||
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
|
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
|
||||||
@@ -232,8 +263,8 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
|
|||||||
return course, nil
|
return course, nil
|
||||||
}
|
}
|
||||||
course.TenantID = tenantID
|
course.TenantID = tenantID
|
||||||
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。
|
// 课程管理关联存在时锁定带出字段(000153;讲师 000161 起计划侧可改)。
|
||||||
s.applyLibraryCourseBinding(ctx, tenantID, course, false)
|
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, false)
|
||||||
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
|
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
|
||||||
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
|
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -242,6 +273,10 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
|
|||||||
if err := s.repo.UpdateCourse(ctx, course); err != nil {
|
if err := s.repo.UpdateCourse(ctx, course); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// 计划侧讲师改动回写课程管理并重置待核验(000161):发布前须重新签核。
|
||||||
|
if old == nil || old.LecturerID != course.LecturerID || old.LecturerExternal != course.LecturerExternal {
|
||||||
|
s.syncPlanLecturerToLibrary(ctx, tenantID, libItem, course, updaterID)
|
||||||
|
}
|
||||||
if old != nil {
|
if old != nil {
|
||||||
s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID)
|
s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID)
|
||||||
}
|
}
|
||||||
@@ -358,15 +393,54 @@ func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id
|
|||||||
if course.Status == types.TrainingCoursePublished {
|
if course.Status == types.TrainingCoursePublished {
|
||||||
return course, nil
|
return course, nil
|
||||||
}
|
}
|
||||||
// 关联课程管理条目须已核验确认(000157):月培训计划发布/保存并发布共用本端点,
|
// 发布必填校验(000161):课程(须关联课程管理且已签核)、参加人员;
|
||||||
// 未核验的课程拦截并友好提示,核验入口在「课程管理」。
|
// 线下计划另需授课时间/授课地点/讲师(线上计划豁免这三项)。
|
||||||
if course.LibraryCourseID != "" {
|
if strings.TrimSpace(course.LibraryCourseID) == "" {
|
||||||
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
|
return nil, errors.NewBadRequestError("发布前需先关联课程管理课程")
|
||||||
if libErr != nil || lib == nil {
|
}
|
||||||
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程")
|
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
|
||||||
|
if libErr != nil || lib == nil {
|
||||||
|
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程")
|
||||||
|
}
|
||||||
|
// 课程须已完成签核(000157/000158):未核验(待核验)时按统一文案拦截,核验入口在「课程管理」。
|
||||||
|
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed {
|
||||||
|
return nil, errors.NewBadRequestError("请联系课长或经理审核课程!").
|
||||||
|
WithDetails(fmt.Sprintf("课程《%s》尚未完成签核,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name))
|
||||||
|
}
|
||||||
|
// 线上计划课件校验(原 handler 前置,收口到 service 统一口径):计划自带课件
|
||||||
|
// 或关联课程的课程管理课件(名称登记/文件/知识库文档,000156 随课程带出)
|
||||||
|
// 任一有值即可;考题非必填,不参与发布校验。
|
||||||
|
if course.Mode == types.TrainingCourseModeOnline {
|
||||||
|
materials, matErr := s.repo.ListMaterials(ctx, tenantID, course.ID)
|
||||||
|
if matErr != nil {
|
||||||
|
return nil, matErr
|
||||||
}
|
}
|
||||||
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed {
|
hasLibCourseware := strings.TrimSpace(lib.MaterialName) != "" ||
|
||||||
return nil, errors.NewBadRequestError(fmt.Sprintf("关联课程《%s》尚未核验确认,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name))
|
strings.TrimSpace(lib.FileKey) != "" ||
|
||||||
|
strings.TrimSpace(lib.KnowledgeID) != ""
|
||||||
|
if len(materials) == 0 && !hasLibCourseware {
|
||||||
|
return nil, errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 参加人员:适用人员非空或场次学员名单有人(跨场次)任一满足即可。
|
||||||
|
if strings.TrimSpace(course.PostScope) == "" {
|
||||||
|
enrolled, enrolledErr := s.repo.CountEnrolledMembersByCourseID(ctx, tenantID, course.ID)
|
||||||
|
if enrolledErr != nil {
|
||||||
|
return nil, enrolledErr
|
||||||
|
}
|
||||||
|
if enrolled == 0 {
|
||||||
|
return nil, errors.NewBadRequestError("发布前需先设置参加人员")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if course.Mode != types.TrainingCourseModeOnline {
|
||||||
|
if strings.TrimSpace(course.TeachTime) == "" {
|
||||||
|
return nil, errors.NewBadRequestError("发布前需先设置授课时间")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(course.Location) == "" {
|
||||||
|
return nil, errors.NewBadRequestError("发布前需先设置授课地点")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(course.LecturerID) == "" && strings.TrimSpace(course.LecturerExternal) == "" {
|
||||||
|
return nil, errors.NewBadRequestError("发布前需先指定讲师")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
course.Status = types.TrainingCoursePublished
|
course.Status = types.TrainingCoursePublished
|
||||||
@@ -578,8 +652,40 @@ func (s *trainingService) CreateMaterial(ctx context.Context, tenantID uint64, m
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListMaterials returns course materials.
|
// ListMaterials returns course materials.
|
||||||
|
// 计划未自带课件时回退关联课程的课程管理课件(000156 随课程带出,发布校验同口径):
|
||||||
|
// 以课程管理条目 id 作为虚拟课件 id 返回,学习详情页预览/文件流/进度上报同链路可用
|
||||||
|
// (GetMaterialFile 对虚拟 id 回退课程管理文件流);仅登记名称而无文件/知识库文档时
|
||||||
|
// 不合成(无内容可打开)。
|
||||||
func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) {
|
func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) {
|
||||||
return s.repo.ListMaterials(ctx, tenantID, courseID)
|
items, err := s.repo.ListMaterials(ctx, tenantID, courseID)
|
||||||
|
if err != nil || len(items) > 0 || courseID == "" {
|
||||||
|
return items, err
|
||||||
|
}
|
||||||
|
course, cErr := s.repo.GetCourse(ctx, tenantID, courseID)
|
||||||
|
if cErr != nil || course == nil || strings.TrimSpace(course.LibraryCourseID) == "" {
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
|
||||||
|
if libErr != nil || lib == nil || (lib.KnowledgeID == "" && lib.FileKey == "") {
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
name := strings.TrimSpace(lib.FileName)
|
||||||
|
if name == "" {
|
||||||
|
name = strings.TrimSpace(lib.MaterialName)
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
name = lib.Name
|
||||||
|
}
|
||||||
|
return []*types.TrainingMaterial{{
|
||||||
|
ID: lib.ID,
|
||||||
|
TenantID: tenantID,
|
||||||
|
CourseID: courseID,
|
||||||
|
Kind: "doc",
|
||||||
|
Name: name,
|
||||||
|
FileKey: lib.FileKey,
|
||||||
|
KnowledgeID: lib.KnowledgeID,
|
||||||
|
Size: lib.FileSize,
|
||||||
|
}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AttachQuestionBank 建课/编辑课时反向关联题库:把 bank.course_id 指向课程,
|
// AttachQuestionBank 建课/编辑课时反向关联题库:把 bank.course_id 指向课程,
|
||||||
|
|||||||
@@ -221,6 +221,11 @@ func trainingKBSummary(kb *types.KnowledgeBase) *types.TrainingKnowledgeBaseSumm
|
|||||||
func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64, materialID string) (io.ReadCloser, string, error) {
|
func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64, materialID string) (io.ReadCloser, string, error) {
|
||||||
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
|
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
|
||||||
|
// 材料行不存在时按课程管理条目取文件流,与发布/学习链路同口径。
|
||||||
|
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID); libErr == nil {
|
||||||
|
return rc, fileName, nil
|
||||||
|
}
|
||||||
return nil, "", werrors.NewNotFoundError("课件不存在")
|
return nil, "", werrors.NewNotFoundError("课件不存在")
|
||||||
}
|
}
|
||||||
if material.KnowledgeID != "" {
|
if material.KnowledgeID != "" {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
@@ -9,6 +10,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
excelize "github.com/xuri/excelize/v2"
|
excelize "github.com/xuri/excelize/v2"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
werrors "academy/internal/errors"
|
werrors "academy/internal/errors"
|
||||||
"academy/internal/logger"
|
"academy/internal/logger"
|
||||||
@@ -107,6 +109,11 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
|||||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||||
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
|
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
|
||||||
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
||||||
|
// 所属部门强制为创建人部门(000160):前端表单同口径锁定,服务端兜底
|
||||||
|
// 覆盖,防止绕过前端改部门。创建人无部门档案时保留原值(可为空)。
|
||||||
|
if member, err := s.CurrentMember(ctx, tenantID, updaterID); err == nil && member != nil && member.DeptID != "" {
|
||||||
|
item.OwnerDeptID = member.DeptID
|
||||||
|
}
|
||||||
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
|
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
|
||||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||||
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||||
@@ -131,6 +138,8 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
|||||||
if item.KnowledgeID == "" {
|
if item.KnowledgeID == "" {
|
||||||
item.KnowledgeID = old.KnowledgeID
|
item.KnowledgeID = old.KnowledgeID
|
||||||
}
|
}
|
||||||
|
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
|
||||||
|
item.OwnerDeptID = old.OwnerDeptID
|
||||||
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
|
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
|
||||||
item.VerifyStatus = types.CourseLibraryVerifyPending
|
item.VerifyStatus = types.CourseLibraryVerifyPending
|
||||||
item.ConfirmedBy = ""
|
item.ConfirmedBy = ""
|
||||||
@@ -215,6 +224,51 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
|
|||||||
return verified, skipped, nil
|
return verified, skipped, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// matchOrCreateLibraryCourse 需求侧课程校验(000158):按课程名称在课程管理精准
|
||||||
|
// 查找,命中直接复用(自动匹配该课程);未命中自动新增该课程——待核验(000157
|
||||||
|
// 流转)、草稿、归属需求部门,由所属部门课长/经理核验,发布前必须已签核完成。
|
||||||
|
// proto 携带需求行带入的名称/部门/讲师/分类/适合人员,其余字段按课程管理默认口径。
|
||||||
|
// 返回条目 id 与是否新建。查询/建档失败一律返回错误(硬失败,不静默跳过),
|
||||||
|
// 由需求保存/导入整批回滚并向前端透出真实原因。
|
||||||
|
func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenantID uint64, proto *types.TrainingCourseLibrary, creatorID string) (string, bool, error) {
|
||||||
|
name := strings.TrimSpace(proto.Name)
|
||||||
|
if name == "" {
|
||||||
|
return "", false, werrors.NewBadRequestError("课程名称不能为空")
|
||||||
|
}
|
||||||
|
hit, err := s.repo.FindCourseLibraryByName(ctx, tenantID, name)
|
||||||
|
switch {
|
||||||
|
case err == nil && hit != nil:
|
||||||
|
return hit.ID, false, nil
|
||||||
|
case !errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
// 查询本身出错(非未命中):不得当作"不存在"去重复建档,直接上抛。
|
||||||
|
return "", false, err
|
||||||
|
}
|
||||||
|
item := &types.TrainingCourseLibrary{
|
||||||
|
ID: trainingNewID(),
|
||||||
|
TenantID: tenantID,
|
||||||
|
Name: name,
|
||||||
|
Code: s.nextCourseLibraryCode(ctx, tenantID),
|
||||||
|
OwnerDeptID: proto.OwnerDeptID,
|
||||||
|
Category: strings.TrimSpace(proto.Category),
|
||||||
|
SuitableMembers: strings.TrimSpace(proto.SuitableMembers),
|
||||||
|
LecturerID: proto.LecturerID,
|
||||||
|
LecturerExternal: strings.TrimSpace(proto.LecturerExternal),
|
||||||
|
Type: "required",
|
||||||
|
Mode: types.TrainingCourseModeOffline,
|
||||||
|
PublishStatus: "draft",
|
||||||
|
VerifyStatus: types.CourseLibraryVerifyPending,
|
||||||
|
CreatorID: creatorID,
|
||||||
|
}
|
||||||
|
if item.LecturerID != "" {
|
||||||
|
item.LecturerExternal = ""
|
||||||
|
}
|
||||||
|
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||||
|
return "", false, err
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "[Training] demand course auto-created to library, tenant=%d course=%s dept=%s creator=%s", tenantID, item.Code, item.OwnerDeptID, creatorID)
|
||||||
|
return item.ID, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
|
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
|
||||||
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
|
||||||
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ type KnowledgeBaseHandler struct {
|
|||||||
// default handle mode is available.
|
// default handle mode is available.
|
||||||
fileService interfaces.FileService
|
fileService interfaces.FileService
|
||||||
storageResolver interfaces.StorageBackendResolver
|
storageResolver interfaces.StorageBackendResolver
|
||||||
|
// bootstrap 幂等自愈空间开箱默认库(新手入门/企业培训课件/题库),挂在
|
||||||
|
// 知识库列表读路径上补齐存量空间缺失的默认库;可为 nil(测试桩)。
|
||||||
|
bootstrap interfaces.TenantBootstrapService
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewKnowledgeBaseHandler creates a new knowledge base handler instance
|
// NewKnowledgeBaseHandler creates a new knowledge base handler instance
|
||||||
@@ -63,6 +66,7 @@ func NewKnowledgeBaseHandler(
|
|||||||
fileService interfaces.FileService,
|
fileService interfaces.FileService,
|
||||||
storageResolver interfaces.StorageBackendResolver,
|
storageResolver interfaces.StorageBackendResolver,
|
||||||
profileService interfaces.KnowledgeBaseProfileService,
|
profileService interfaces.KnowledgeBaseProfileService,
|
||||||
|
bootstrap interfaces.TenantBootstrapService,
|
||||||
) *KnowledgeBaseHandler {
|
) *KnowledgeBaseHandler {
|
||||||
return &KnowledgeBaseHandler{
|
return &KnowledgeBaseHandler{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
@@ -76,6 +80,7 @@ func NewKnowledgeBaseHandler(
|
|||||||
userService: userService,
|
userService: userService,
|
||||||
fileService: fileService,
|
fileService: fileService,
|
||||||
storageResolver: storageResolver,
|
storageResolver: storageResolver,
|
||||||
|
bootstrap: bootstrap,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -639,6 +644,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 开箱默认库惰性自愈(幂等/fail-open):注册引导是一次性动作,存量空间因
|
||||||
|
// 引导当时失败或保留租户 id 碰撞(migration 000160 前首空间占住 10000)
|
||||||
|
// 而缺失默认库时,访问列表即补齐——培训课件/题库两库恒补,新手入门仅
|
||||||
|
// 零库空间补建。补建后本次查询即可见。
|
||||||
|
if h.bootstrap != nil {
|
||||||
|
h.bootstrap.EnsureTenantDefaultKnowledgeBases(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// Get all knowledge bases for this tenant
|
// Get all knowledge bases for this tenant
|
||||||
kbs, err := h.service.ListKnowledgeBases(ctx)
|
kbs, err := h.service.ListKnowledgeBases(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package orgcenter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -199,6 +200,69 @@ func (h *Handler) ListPlatformUsers(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 归属空间收编(登录默认落点;路由层 Owner 限定,与成员批量导入同权限级别)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// orgAdoptMaxUsers 单次收编人数上限(与成员批量导入行数上限同量级,防超大批次)。
|
||||||
|
const orgAdoptMaxUsers = 2000
|
||||||
|
|
||||||
|
// ListAdoptableUsers GET /org/employees/adoptable — 收编预览:归属空间不在
|
||||||
|
// 本空间的活跃成员(员工首登开了个人空间时,登录会落进个人空间看不到本空间
|
||||||
|
// 维护的组织架构,管理员用收编把默认落点改回本空间)。
|
||||||
|
func (h *Handler) ListAdoptableUsers(c *gin.Context) {
|
||||||
|
users, err := h.svc.ListAdoptableUsers(c.Request.Context(), callerTenantID(c))
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
|
||||||
|
}
|
||||||
|
|
||||||
|
// adoptHomeTenantRequest is the body of POST /org/employees/adopt-home.
|
||||||
|
type adoptHomeTenantRequest struct {
|
||||||
|
UserIDs []string `json:"user_ids" binding:"required,min=1"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdoptHomeTenant POST /org/employees/adopt-home — 批量收编归属空间到本空间。
|
||||||
|
// 只改成员的登录默认落点(users.tenant_id + 最近活跃租户偏好),不动成员关系
|
||||||
|
// 与个人空间数据;逐条跳过非本空间成员等情形并回传原因。
|
||||||
|
func (h *Handler) AdoptHomeTenant(c *gin.Context) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
var req adoptHomeTenantRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(req.UserIDs) > orgAdoptMaxUsers {
|
||||||
|
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("单次最多收编 %d 名成员", orgAdoptMaxUsers)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 去重保序:重复/空 id 只收编一次,统计口径不重复计数。
|
||||||
|
seen := make(map[string]struct{}, len(req.UserIDs))
|
||||||
|
userIDs := make([]string, 0, len(req.UserIDs))
|
||||||
|
for _, id := range req.UserIDs {
|
||||||
|
if id == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, dup := seen[id]; dup {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
userIDs = append(userIDs, id)
|
||||||
|
}
|
||||||
|
if len(userIDs) == 0 {
|
||||||
|
_ = c.Error(errors.NewBadRequestError("请选择要收编的成员"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result, err := h.svc.AdoptHomeTenant(ctx, callerTenantID(c), userIDs)
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 模块角色绑定
|
// 模块角色绑定
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -216,8 +280,8 @@ func (h *Handler) ListModuleMembers(c *gin.Context) {
|
|||||||
|
|
||||||
// putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id.
|
// putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id.
|
||||||
type putModuleMemberRequest struct {
|
type putModuleMemberRequest struct {
|
||||||
Roles []string `json:"roles"`
|
Roles []string `json:"roles"`
|
||||||
Extra map[string]any `json:"extra"`
|
Extra map[string]any `json:"extra"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PutModuleMember PUT /org/modules/:module_key/members/:employee_id
|
// PutModuleMember PUT /org/modules/:module_key/members/:employee_id
|
||||||
|
|||||||
@@ -32,12 +32,41 @@ func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotifi
|
|||||||
return &Handler{svc: svc, pusher: pusher}
|
return &Handler{svc: svc, pusher: pusher}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trainingTenantContextKey 培训域解析后的数据空间租户 id(000160):由
|
||||||
|
// TrainingTenantResolution 中间件写入,callerTenantID 优先读取。
|
||||||
|
const trainingTenantContextKey = "training_tenant_id"
|
||||||
|
|
||||||
|
// TrainingTenantResolution 企业培训数据空间解析中间件(000160):认证守卫之后
|
||||||
|
// 执行,按「当前空间有培训档案优先,否则回退员工档案所在空间」解析培训域实际
|
||||||
|
// 读写的租户并写入上下文;本组所有 handler 的 callerTenantID 均取解析值 ——
|
||||||
|
// 同一组织的人员切换到任意工作区,都能看到并参与其档案所属组织的企业培训。
|
||||||
|
func (h *Handler) TrainingTenantResolution() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
active := c.GetUint64(types.TenantIDContextKey.String())
|
||||||
|
userID := callerUserID(c)
|
||||||
|
if active != 0 && userID != "" {
|
||||||
|
if resolved, err := h.svc.ResolveTrainingTenant(c.Request.Context(), active, userID); err == nil && resolved != 0 {
|
||||||
|
c.Set(trainingTenantContextKey, resolved)
|
||||||
|
// 执行租户随培训空间同步回落(000160):课件文件流(GetKnowledgeFile)、
|
||||||
|
// 培训知识库 ensure 等按 ctx 租户读写的服务链路才落在档案所在空间;
|
||||||
|
// caller 身份保持当前工作区不变,授权口径不受影响。
|
||||||
|
c.Request = c.Request.WithContext(types.WithExecutionTenant(c.Request.Context(), resolved))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 请求上下文辅助
|
// 请求上下文辅助
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// callerTenantID reads the tenant id injected by the auth middleware.
|
// callerTenantID reads the tenant id injected by the auth middleware, or the
|
||||||
|
// training-resolved tenant (000160) when the route group middleware resolved one.
|
||||||
func callerTenantID(c *gin.Context) uint64 {
|
func callerTenantID(c *gin.Context) uint64 {
|
||||||
|
if v := c.GetUint64(trainingTenantContextKey); v != 0 {
|
||||||
|
return v
|
||||||
|
}
|
||||||
return c.GetUint64(types.TenantIDContextKey.String())
|
return c.GetUint64(types.TenantIDContextKey.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,6 +429,18 @@ func (h *Handler) Me(c *gin.Context) {
|
|||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// 联查部门名(000160):员工档案只存 dept_id,前端课程目录按部门名匹配
|
||||||
|
// 「适合人员」、表单默认值展示均需要名称;档案无部门时保持空串。
|
||||||
|
if member.DeptID != "" {
|
||||||
|
if depts, err := h.svc.ListDepts(ctx, callerTenantID(c)); err == nil {
|
||||||
|
for _, d := range depts {
|
||||||
|
if d.ID == member.DeptID {
|
||||||
|
member.DeptName = d.Name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -436,9 +477,12 @@ func (h *Handler) ListDemandYears(c *gin.Context) {
|
|||||||
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
|
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
|
||||||
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
|
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
|
||||||
type saveDemandRequest struct {
|
type saveDemandRequest struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Year int `json:"year"`
|
Year int `json:"year"`
|
||||||
DeptID string `json:"dept_id"`
|
DeptID string `json:"dept_id"`
|
||||||
|
// DeptName Excel「部门」列原始值(仅批量导入部门归属校验用,000158:全部行
|
||||||
|
// 必须为导入人本人部门;在线提报不传,服务端强制按提报人部门落库)。
|
||||||
|
DeptName string `json:"dept_name"`
|
||||||
CourseName string `json:"course_name" binding:"required"`
|
CourseName string `json:"course_name" binding:"required"`
|
||||||
Plant string `json:"plant"`
|
Plant string `json:"plant"`
|
||||||
Category string `json:"category"`
|
Category string `json:"category"`
|
||||||
@@ -504,14 +548,23 @@ func (h *Handler) SaveDemand(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。
|
// 部门口径(000158):所属部门必须为填报人本人部门——新建强制按提报人所在
|
||||||
deptID := trimSpace(req.DeptID)
|
// 部门(org_employees.dept_id)落库,忽略请求值防绕过;编辑保留原部门(人事
|
||||||
if deptID == "" {
|
// 代改也不覆盖归属)。提报人无部门档案时阻断,先由人事在组织中心维护。
|
||||||
if existing != nil {
|
var deptID string
|
||||||
deptID = existing.DeptID
|
if existing != nil {
|
||||||
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil {
|
deptID = existing.DeptID
|
||||||
deptID = member.DeptID
|
} else {
|
||||||
|
member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c))
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Error(err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
if member == nil || trimSpace(member.DeptID) == "" {
|
||||||
|
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再提报"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
deptID = member.DeptID
|
||||||
}
|
}
|
||||||
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
|
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
|
||||||
ID: req.ID, Year: req.Year, DeptID: deptID,
|
ID: req.ID, Year: req.Year, DeptID: deptID,
|
||||||
@@ -575,6 +628,9 @@ func (h *Handler) ListPosts(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。
|
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。
|
||||||
|
// 部门口径(000158):全部行必须为导入人本人部门(org_employees.dept_id,全员
|
||||||
|
// 严格,人事也不例外);部门列留空视为默认导入人部门,其余任一行不符即整批
|
||||||
|
// 拒绝。导入人无部门档案时阻断,先由人事在组织中心维护。
|
||||||
func (h *Handler) ImportDemands(c *gin.Context) {
|
func (h *Handler) ImportDemands(c *gin.Context) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||||
@@ -587,10 +643,47 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
|||||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
tenantID, userID := callerTenantID(c), callerUserID(c)
|
||||||
|
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if member == nil || trimSpace(member.DeptID) == "" {
|
||||||
|
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再导入"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 整批部门预检:任一行部门与导入人不符即拒绝,不做部分导入。
|
||||||
|
// 通过口径:行部门 id 与本人一致,或部门列全空(默认导入人部门)。
|
||||||
|
myDeptName := h.deptNameOf(ctx, tenantID, member.DeptID)
|
||||||
|
violations := make([]string, 0, len(req.Demands))
|
||||||
|
for i, item := range req.Demands {
|
||||||
|
deptID, deptName := trimSpace(item.DeptID), trimSpace(item.DeptName)
|
||||||
|
if deptID == "" && deptName == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if deptID == member.DeptID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if deptName == "" {
|
||||||
|
deptName = h.deptNameOf(ctx, tenantID, deptID)
|
||||||
|
}
|
||||||
|
if deptName == "" {
|
||||||
|
deptName = deptID
|
||||||
|
}
|
||||||
|
violations = append(violations, fmt.Sprintf("第%d行(%s)", i+1, deptName))
|
||||||
|
}
|
||||||
|
if len(violations) > 0 {
|
||||||
|
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf(
|
||||||
|
"导入失败:第%s行部门与您所在部门(%s)不一致,仅可导入本人部门的需求表",
|
||||||
|
strings.Join(violations, "、"), myDeptName)))
|
||||||
|
return
|
||||||
|
}
|
||||||
demands := make([]*types.TrainingDemand, 0, len(req.Demands))
|
demands := make([]*types.TrainingDemand, 0, len(req.Demands))
|
||||||
for _, item := range req.Demands {
|
for _, item := range req.Demands {
|
||||||
demands = append(demands, &types.TrainingDemand{
|
demands = append(demands, &types.TrainingDemand{
|
||||||
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName,
|
// 部门强制为导入人本人部门:部门列留空的行在此默认,其余已通过预检。
|
||||||
|
Year: item.Year, DeptID: member.DeptID, CourseName: item.CourseName,
|
||||||
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
|
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
|
||||||
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
|
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
|
||||||
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
|
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
|
||||||
@@ -598,16 +691,34 @@ func (h *Handler) ImportDemands(c *gin.Context) {
|
|||||||
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
|
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
result, err := h.svc.ImportDemands(ctx, callerTenantID(c), demands, callerUserID(c))
|
result, coursesCreated, err := h.svc.ImportDemands(ctx, tenantID, demands, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
|
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
|
||||||
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
|
h.syncDemandLecturerToLibrary(ctx, tenantID, userID, demands)
|
||||||
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
|
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
|
||||||
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands)
|
notified := h.notifyDemandVerify(ctx, tenantID, demands)
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}})
|
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
|
||||||
|
"imported": len(result), "notified": notified, "courses_created": coursesCreated}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// deptNameOf 部门 id → 名称(导入报错文案用;查不到时回退展示 id)。
|
||||||
|
func (h *Handler) deptNameOf(ctx context.Context, tenantID uint64, deptID string) string {
|
||||||
|
if trimSpace(deptID) == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
depts, err := h.svc.ListDepts(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return deptID
|
||||||
|
}
|
||||||
|
for _, d := range depts {
|
||||||
|
if d != nil && d.ID == deptID {
|
||||||
|
return d.Name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deptID
|
||||||
}
|
}
|
||||||
|
|
||||||
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
|
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
|
||||||
@@ -681,10 +792,13 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
|
|||||||
PostScope: demand.PostScope,
|
PostScope: demand.PostScope,
|
||||||
}
|
}
|
||||||
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
|
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
|
||||||
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
|
// 课程管理关联(000158):需求填报/导入时已按名称精准匹配并回填
|
||||||
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
|
// library_course_id(未命中自动新增待核验课程),此处直接采用;存量需求
|
||||||
|
// 无值时回退课程管理同名扫描兜底(计划侧自动带出并锁定课程信息)。
|
||||||
course.SourceDemandID = demand.ID
|
course.SourceDemandID = demand.ID
|
||||||
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
|
if trimSpace(demand.LibraryCourseID) != "" {
|
||||||
|
course.LibraryCourseID = demand.LibraryCourseID
|
||||||
|
} else if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
|
||||||
for _, item := range libItems {
|
for _, item := range libItems {
|
||||||
if item != nil && item.Name == demand.CourseName {
|
if item != nil && item.Name == demand.CourseName {
|
||||||
course.LibraryCourseID = item.ID
|
course.LibraryCourseID = item.ID
|
||||||
@@ -901,47 +1015,75 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
|
// syncDemandLecturerToLibrary 需求课程信息回写课程管理(000156/000161):需求
|
||||||
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
|
// (导入/在线保存/编辑)所关联的课程管理条目——优先 demand.library_course_id
|
||||||
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
|
// (000158 自动匹配),无值回退同名匹配——讲师与条目不一致时以需求为准更新;
|
||||||
|
// 000161 扩展:分类/适合人员(需求侧改后)同样回写。SaveCourseLibraryItem 的
|
||||||
|
// 编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须重新签核。
|
||||||
|
// 同批同名取首条。fail-open:失败仅记日志不阻断保存/导入。
|
||||||
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
|
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
|
||||||
|
byID := map[string]*types.TrainingDemand{}
|
||||||
byName := map[string]*types.TrainingDemand{}
|
byName := map[string]*types.TrainingDemand{}
|
||||||
for _, d := range demands {
|
for _, d := range demands {
|
||||||
if d == nil || trimSpace(d.CourseName) == "" {
|
if d == nil || trimSpace(d.CourseName) == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" {
|
if id := trimSpace(d.LibraryCourseID); id != "" {
|
||||||
|
if _, ok := byID[id]; !ok {
|
||||||
|
byID[id] = d
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if _, ok := byName[d.CourseName]; !ok {
|
if _, ok := byName[d.CourseName]; !ok {
|
||||||
byName[d.CourseName] = d
|
byName[d.CourseName] = d
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(byName) == 0 {
|
if len(byID) == 0 && len(byName) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
|
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error(ctx, "Failed to list course library for lecturer sync", err)
|
logger.Error(ctx, "Failed to list course library for demand sync", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
if item == nil {
|
if item == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
d, ok := byName[item.Name]
|
d, ok := byID[item.ID]
|
||||||
|
if !ok {
|
||||||
|
d, ok = byName[item.Name]
|
||||||
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
|
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
|
||||||
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
|
if lecturerID != "" {
|
||||||
|
lecturerExt = ""
|
||||||
|
}
|
||||||
|
hasLecturer := lecturerID != "" || lecturerExt != ""
|
||||||
|
category, suitable := trimSpace(d.Category), trimSpace(d.PostScope)
|
||||||
|
// 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止
|
||||||
|
// 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。
|
||||||
|
changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) ||
|
||||||
|
(category != "" && item.Category != category) ||
|
||||||
|
(suitable != "" && item.SuitableMembers != suitable)
|
||||||
|
if !changed {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
updated := *item
|
updated := *item
|
||||||
updated.LecturerID = lecturerID
|
if hasLecturer {
|
||||||
updated.LecturerExternal = lecturerExt
|
updated.LecturerID = lecturerID
|
||||||
|
updated.LecturerExternal = lecturerExt
|
||||||
|
}
|
||||||
|
if category != "" {
|
||||||
|
updated.Category = category
|
||||||
|
}
|
||||||
|
if suitable != "" {
|
||||||
|
updated.SuitableMembers = suitable
|
||||||
|
}
|
||||||
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
|
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
|
||||||
logger.Error(ctx, "Failed to sync demand lecturer to course library", err)
|
logger.Error(ctx, "Failed to sync demand course info to course library", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
|
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
|
||||||
@@ -1221,26 +1363,8 @@ func (h *Handler) PublishCourse(c *gin.Context) {
|
|||||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。
|
// 发布前置校验(线上课件/线下讲师等)统一收口在 service PublishCourse:
|
||||||
course, err := h.svc.GetCourse(ctx, callerTenantID(c), c.Param("id"))
|
// 线上课件认计划自带或课程管理自带课件,考题非必填。
|
||||||
if err != nil {
|
|
||||||
_ = c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if course.Mode == "online" {
|
|
||||||
materials, err := h.svc.ListMaterials(ctx, callerTenantID(c), course.ID)
|
|
||||||
if err != nil {
|
|
||||||
_ = c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(materials) == 0 {
|
|
||||||
_ = c.Error(errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else if trimSpace(course.LecturerID) == "" {
|
|
||||||
_ = c.Error(errors.NewBadRequestError("线下课程发布前需先指定讲师"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
|
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
|
|||||||
@@ -66,9 +66,31 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
|
|||||||
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
|
||||||
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
|
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
|
||||||
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
|
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
|
||||||
|
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方
|
||||||
|
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护
|
||||||
|
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
|
||||||
func (h *Handler) ListCourseLibrary(c *gin.Context) {
|
func (h *Handler) ListCourseLibrary(c *gin.Context) {
|
||||||
q := listQueryFromRequest(c)
|
q := listQueryFromRequest(c)
|
||||||
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
|
if q.Scope == "catalog" {
|
||||||
|
q.CatalogOnly = true
|
||||||
|
// 调用方部门(id+名)用于适合人员匹配;无培训档案的调用方两个字段
|
||||||
|
// 留空(仅见「全部」与未设置适合人员的课程),不阻断目录查询。
|
||||||
|
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
|
||||||
|
q.CatalogDeptID = member.DeptID
|
||||||
|
}
|
||||||
|
if q.CatalogDeptID != "" {
|
||||||
|
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
|
||||||
|
for _, d := range depts {
|
||||||
|
if d.ID == q.CatalogDeptID {
|
||||||
|
q.CatalogDeptName = d.Name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
|
||||||
|
}
|
||||||
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q)
|
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -337,7 +337,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||||||
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
|
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
|
||||||
RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
|
RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
|
||||||
RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards)
|
RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards)
|
||||||
RegisterOrgRoutes(v1, params.OrgCenterHandler, rbacGuards)
|
RegisterOrgRoutes(v1, params.OrgCenterHandler, params.TrainingHandler, rbacGuards)
|
||||||
RegisterChunkerDebugRoutes(v1, rbacGuards)
|
RegisterChunkerDebugRoutes(v1, rbacGuards)
|
||||||
|
|
||||||
// Fail fast if any declared API-key policy points at a route
|
// Fail fast if any declared API-key policy points at a route
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package router
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"academy/internal/handler/orgcenter"
|
"academy/internal/handler/orgcenter"
|
||||||
|
"academy/internal/handler/training"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -11,7 +12,12 @@ import (
|
|||||||
// - 空间 RBAC 把关:读 Viewer+,写 Contributor+;
|
// - 空间 RBAC 把关:读 Viewer+,写 Contributor+;
|
||||||
// - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知;
|
// - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知;
|
||||||
// - 不对 API Key 开放(组织数据面向登录用户,默认拒绝)。
|
// - 不对 API Key 开放(组织数据面向登录用户,默认拒绝)。
|
||||||
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards) {
|
//
|
||||||
|
// th 为培训域 handler,可空:职称角色/企微账号维护自培训域迁入组织架构页后,
|
||||||
|
// /org 域提供同名写接口(直接复用培训 handler —— 其 requireRoles 基于
|
||||||
|
// callerTenantID 做角色细控,与 org 域租户口径一致,且不经培训域的
|
||||||
|
// TrainingTenantResolution 租户回落,跨空间 HR 在组织架构页操作不会错绑租户)。
|
||||||
|
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, th *training.Handler, g *rbacGuards) {
|
||||||
if h == nil {
|
if h == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -28,6 +34,23 @@ func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards)
|
|||||||
orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers)
|
orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers)
|
||||||
orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees)
|
orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees)
|
||||||
|
|
||||||
|
// ---- 归属空间收编(登录默认落点) ----
|
||||||
|
// Owner 限定:改的是账号级登录落点(users.tenant_id + 最近活跃租户偏好),
|
||||||
|
// 与成员批量导入/ Casdoor 同步同权限级别,组织架构页仅 Owner 可见入口。
|
||||||
|
orgGroup.GET("/employees/adoptable", g.Owner(), h.ListAdoptableUsers)
|
||||||
|
orgGroup.POST("/employees/adopt-home", g.Owner(), h.AdoptHomeTenant)
|
||||||
|
|
||||||
|
// ---- 职称角色 / 企微账号(培训域语义,handler 内 requireRoles(HR,经理) 细控) ----
|
||||||
|
// 职称角色页(培训 members 子页)迁入组织架构页后的 /org 域别名路由:
|
||||||
|
// 复用培训 handler,角色绑定仍写 module_key='training' 的 org_module_members。
|
||||||
|
if th != nil {
|
||||||
|
orgGroup.PUT("/employees/:id/roles", g.Contributor(), th.UpdateMemberRoles)
|
||||||
|
orgGroup.PUT("/employees/:id/wecom-userid", g.Contributor(), th.UpdateMemberWecomUserid)
|
||||||
|
// wecom-userid-sync 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式)。
|
||||||
|
orgGroup.POST("/employees/wecom-userid-sync/preview", g.Contributor(), th.SyncWecomUseridsPreview)
|
||||||
|
orgGroup.POST("/employees/wecom-userid-sync/apply", g.Contributor(), th.SyncWecomUseridsApply)
|
||||||
|
}
|
||||||
|
|
||||||
// ---- 模块角色绑定 ----
|
// ---- 模块角色绑定 ----
|
||||||
orgGroup.GET("/modules/:module_key/members", h.ListModuleMembers)
|
orgGroup.GET("/modules/:module_key/members", h.ListModuleMembers)
|
||||||
orgGroup.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember)
|
orgGroup.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember)
|
||||||
|
|||||||
@@ -24,7 +24,10 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
|||||||
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
|
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
|
||||||
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
|
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
|
||||||
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
|
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
|
||||||
trainingGroup := r.Group("/training", g.Viewer())
|
// TrainingTenantResolution(000160):培训域数据空间按员工档案归属解析 ——
|
||||||
|
// 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在
|
||||||
|
// 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。
|
||||||
|
trainingGroup := r.Group("/training", g.Viewer(), h.TrainingTenantResolution())
|
||||||
{
|
{
|
||||||
// ---- 我的档案(角色决定工作台渲染) ----
|
// ---- 我的档案(角色决定工作台渲染) ----
|
||||||
trainingGroup.GET("/members/me", h.Me)
|
trainingGroup.GET("/members/me", h.Me)
|
||||||
|
|||||||
@@ -50,6 +50,13 @@ const (
|
|||||||
// AuditActionInvitationExpired fires when the lazy sweep transitions
|
// AuditActionInvitationExpired fires when the lazy sweep transitions
|
||||||
// an overdue pending row to expired. Actor is empty (system).
|
// an overdue pending row to expired. Actor is empty (system).
|
||||||
AuditActionInvitationExpired AuditAction = "rbac.invitation_expired"
|
AuditActionInvitationExpired AuditAction = "rbac.invitation_expired"
|
||||||
|
// AuditActionMemberHomeAdopted fires when a tenant Owner batch-adopts
|
||||||
|
// members' home tenants (users.tenant_id + LastActiveTenantID) into the
|
||||||
|
// operating workspace (组织架构「收编到本空间」). The membership rows are
|
||||||
|
// untouched — only the default-landing pointer moves — so this is
|
||||||
|
// distinct from member_added. Details payload carries
|
||||||
|
// {user_ids, adopted, skipped} for batch reconciliation.
|
||||||
|
AuditActionMemberHomeAdopted AuditAction = "rbac.member_home_adopted"
|
||||||
|
|
||||||
// VectorStore lifecycle actions. Emitted by VectorStoreService.
|
// VectorStore lifecycle actions. Emitted by VectorStoreService.
|
||||||
// Cover both env-store-derived (__env_*) and DB store create /
|
// Cover both env-store-derived (__env_*) and DB store create /
|
||||||
|
|||||||
@@ -22,14 +22,21 @@ type OrgCenterRepository interface {
|
|||||||
GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error)
|
GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error)
|
||||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
||||||
UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error
|
UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error
|
||||||
|
// InsertEmployeesIfAbsent 成员加入时自动入册:按 (tenant, user_id) 补建,
|
||||||
|
// 仅回填为空的工号/部门,不覆盖人工维护字段。
|
||||||
|
InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error
|
||||||
UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error
|
UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error
|
||||||
DeleteEmployee(ctx context.Context, tenantID uint64, id string) error
|
DeleteEmployee(ctx context.Context, tenantID uint64, id string) error
|
||||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||||
|
|
||||||
// ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。
|
// ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。
|
||||||
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
||||||
|
// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。
|
||||||
|
ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error)
|
||||||
// GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。
|
// GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。
|
||||||
GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error)
|
GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error)
|
||||||
|
// GetRosterUserInfos 指定成员的入册所需字段(平台账号 + 同步部门)。
|
||||||
|
GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error)
|
||||||
|
|
||||||
// ---- 模块角色绑定 ----
|
// ---- 模块角色绑定 ----
|
||||||
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
|
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
|
||||||
@@ -52,12 +59,21 @@ type OrgCenterService interface {
|
|||||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
||||||
// ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。
|
// ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。
|
||||||
ImportEmployees(ctx context.Context, tenantID uint64, employees []*types.OrgEmployee) (int, error)
|
ImportEmployees(ctx context.Context, tenantID uint64, employees []*types.OrgEmployee) (int, error)
|
||||||
|
// EnsureEmployeesForUsers 成员加入空间时自动入册:按平台账号补建员工档案,
|
||||||
|
// 部门按同步字段(dept_code 优先/dept_name 兜底)自动匹配;fail-open 不阻断入伙。
|
||||||
|
EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error
|
||||||
UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error)
|
UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error)
|
||||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||||
|
|
||||||
// ListTenantUsers 平台用户列表(员工导入选择器数据源)。
|
// ListTenantUsers 平台用户列表(员工导入选择器数据源)。
|
||||||
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
||||||
|
|
||||||
|
// ListAdoptableUsers 归属空间不在本空间的活跃成员列表(收编预览)。
|
||||||
|
ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error)
|
||||||
|
// AdoptHomeTenant 批量收编:把指定成员的归属空间(登录默认落点)改为本空间。
|
||||||
|
// 仅收编本空间活跃成员,逐条跳过并回传原因;成功后补跑一次自动入册。
|
||||||
|
AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error)
|
||||||
|
|
||||||
// 模块角色绑定
|
// 模块角色绑定
|
||||||
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
|
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
|
||||||
PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error)
|
PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error)
|
||||||
|
|||||||
@@ -17,4 +17,12 @@ type TenantBootstrapService interface {
|
|||||||
// bootstrap knowledge base are skipped. ownerUserID (may be empty for
|
// bootstrap knowledge base are skipped. ownerUserID (may be empty for
|
||||||
// platform-managed tenants) is recorded as the KB creator.
|
// platform-managed tenants) is recorded as the KB creator.
|
||||||
SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string)
|
SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string)
|
||||||
|
|
||||||
|
// EnsureTenantDefaultKnowledgeBases lazily self-heals a workspace's
|
||||||
|
// out-of-the-box defaults on list access: the two enterprise-training KBs
|
||||||
|
// are always ensured (Source-marker idempotent), and the starter KB is
|
||||||
|
// re-created only when the workspace has no knowledge bases at all (a
|
||||||
|
// seed that never succeeded). Idempotent and fail-open — safe to call on
|
||||||
|
// read paths. The execution tenant is taken from the context.
|
||||||
|
EnsureTenantDefaultKnowledgeBases(ctx context.Context)
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,13 @@ type TrainingListQuery struct {
|
|||||||
Keyword string
|
Keyword string
|
||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
|
// 课程管理学员目录口径(000160,scope=catalog 时 handler 注入):
|
||||||
|
// CatalogOnly 仅返回已发布课程,且适合人员须覆盖调用方 ——
|
||||||
|
// suitable='全部' 或 =调用方部门名;未设置适合人员的存量课程沿用
|
||||||
|
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。
|
||||||
|
CatalogOnly bool
|
||||||
|
CatalogDeptID string
|
||||||
|
CatalogDeptName string
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
|
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
|
||||||
@@ -42,6 +49,9 @@ type TrainingRepository interface {
|
|||||||
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。
|
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。
|
||||||
GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error)
|
GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error)
|
||||||
GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
|
GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
|
||||||
|
// FindArchiveTenantID 跨租户定位用户最早在职员工档案(org_employees)的租户
|
||||||
|
// (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。
|
||||||
|
FindArchiveTenantID(ctx context.Context, userID string) (uint64, error)
|
||||||
// ListLecturers/ListPosts 需求提报表单的下拉数据源(讲师名册/实际岗位)。
|
// ListLecturers/ListPosts 需求提报表单的下拉数据源(讲师名册/实际岗位)。
|
||||||
ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error)
|
ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error)
|
||||||
ListPosts(ctx context.Context, tenantID uint64) ([]string, error)
|
ListPosts(ctx context.Context, tenantID uint64) ([]string, error)
|
||||||
@@ -83,6 +93,8 @@ type TrainingRepository interface {
|
|||||||
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
|
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
|
||||||
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
|
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
|
||||||
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
|
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
|
||||||
|
// FindCourseLibraryByName 按课程名称精准查找课程条目(000158 需求侧课程自动匹配)。
|
||||||
|
FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error)
|
||||||
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
||||||
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
|
||||||
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
|
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
|
||||||
@@ -102,6 +114,8 @@ type TrainingRepository interface {
|
|||||||
ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
|
ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
|
||||||
// CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。
|
// CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。
|
||||||
CountEnrolledMembersByCourse(ctx context.Context, tenantID uint64) (map[string]int, error)
|
CountEnrolledMembersByCourse(ctx context.Context, tenantID uint64) (map[string]int, error)
|
||||||
|
// CountEnrolledMembersByCourseID 单课程场次学员名单人数(发布必填校验,000161)。
|
||||||
|
CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error)
|
||||||
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(课程管理列表学习/考试状态列)。
|
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(课程管理列表学习/考试状态列)。
|
||||||
CourseStudyStats(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error)
|
CourseStudyStats(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error)
|
||||||
// CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。
|
// CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。
|
||||||
@@ -265,6 +279,9 @@ type TrainingService interface {
|
|||||||
SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error)
|
SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error)
|
||||||
// CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。
|
// CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。
|
||||||
CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
|
CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
|
||||||
|
// ResolveTrainingTenant 企业培训数据空间解析(000160):当前空间有培训档案
|
||||||
|
// 用当前空间;否则回退到最早在职员工档案所在空间;都没有维持当前空间。
|
||||||
|
ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error)
|
||||||
|
|
||||||
// 计划域
|
// 计划域
|
||||||
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
|
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
|
||||||
@@ -272,7 +289,8 @@ type TrainingService interface {
|
|||||||
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
|
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
|
||||||
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
|
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
|
||||||
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
|
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
|
||||||
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error)
|
// ImportDemands 批量导入需求;返回导入行与自动新增的待核验课程数(000158)。
|
||||||
|
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error)
|
||||||
ConfirmDemand(ctx context.Context, tenantID uint64, id string, updaterID string) (*types.TrainingDemand, error)
|
ConfirmDemand(ctx context.Context, tenantID uint64, id string, updaterID string) (*types.TrainingDemand, error)
|
||||||
DeleteDemand(ctx context.Context, tenantID uint64, id string) error
|
DeleteDemand(ctx context.Context, tenantID uint64, id string) error
|
||||||
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
|
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
|
||||||
|
|||||||
+55
-27
@@ -23,14 +23,14 @@ const (
|
|||||||
|
|
||||||
// OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。
|
// OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。
|
||||||
type OrgDept struct {
|
type OrgDept struct {
|
||||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||||
ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"`
|
ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"`
|
||||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||||
Code string `json:"code" gorm:"type:varchar(64);default:''"`
|
Code string `json:"code" gorm:"type:varchar(64);default:''"`
|
||||||
Sort int `json:"sort" gorm:"default:0"`
|
Sort int `json:"sort" gorm:"default:0"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,17 +39,17 @@ func (OrgDept) TableName() string { return "org_depts" }
|
|||||||
|
|
||||||
// OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。
|
// OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。
|
||||||
type OrgEmployee struct {
|
type OrgEmployee struct {
|
||||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||||
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"`
|
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"`
|
||||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"`
|
UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"`
|
||||||
EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"`
|
EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"`
|
||||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"`
|
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"`
|
||||||
Post string `json:"post" gorm:"type:varchar(128);default:''"`
|
Post string `json:"post" gorm:"type:varchar(128);default:''"`
|
||||||
LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"`
|
LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"`
|
||||||
WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"`
|
WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"`
|
||||||
Status string `json:"status" gorm:"type:varchar(16);default:'active'"`
|
Status string `json:"status" gorm:"type:varchar(16);default:'active'"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||||
|
|
||||||
// 联查只读展示字段(不落库):
|
// 联查只读展示字段(不落库):
|
||||||
@@ -76,14 +76,14 @@ func (m *OrgEmployee) OrgRoleList() []string {
|
|||||||
|
|
||||||
// OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。
|
// OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。
|
||||||
type OrgModuleMember struct {
|
type OrgModuleMember struct {
|
||||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||||
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"`
|
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"`
|
||||||
ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"`
|
ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"`
|
||||||
EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"`
|
EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"`
|
||||||
Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"`
|
Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"`
|
||||||
Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"`
|
Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DeletedAt *time.Time `json:"-" gorm:"index"`
|
DeletedAt *time.Time `json:"-" gorm:"index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,3 +97,31 @@ type OrgListQuery struct {
|
|||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OrgAdoptableUser 可收编成员(归属空间不在本空间的活跃成员),「收编到本空间」
|
||||||
|
// 预览行。归属空间(users.tenant_id)决定登录/refresh 默认进入的工作区;员工
|
||||||
|
// 首登自动开通个人空间(create_personal 默认)后归属指针停在个人空间,收编把
|
||||||
|
// 该指针改指本空间——成员关系、角色与个人空间数据均不变,非破坏性。
|
||||||
|
type OrgAdoptableUser struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
HomeTenantID uint64 `json:"home_tenant_id"`
|
||||||
|
HomeTenantName string `json:"home_tenant_name"`
|
||||||
|
InRoster bool `json:"in_roster"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrgAdoptSkip 批量收编中单条跳过记录(逐条原因回传 UI 展示)。
|
||||||
|
type OrgAdoptSkip struct {
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Reason string `json:"reason"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrgAdoptResult 批量收编结果统计。
|
||||||
|
type OrgAdoptResult struct {
|
||||||
|
Adopted int `json:"adopted"`
|
||||||
|
Skipped []*OrgAdoptSkip `json:"skipped"`
|
||||||
|
}
|
||||||
+17
-12
@@ -363,16 +363,20 @@ type TrainingDemand struct {
|
|||||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||||
Year int `json:"year" gorm:"not null;index"`
|
Year int `json:"year" gorm:"not null;index"`
|
||||||
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
|
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
|
||||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||||
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
|
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
|
||||||
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
|
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
|
||||||
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
|
// LibraryCourseID 需求所填课程自动匹配的课程管理条目 id(000158):填报/导入时
|
||||||
Category string `json:"category" gorm:"type:varchar(32);default:''"`
|
// 按课程名称精准查找,命中回填;未命中自动新增该课程(待核验)后回填,确认转
|
||||||
SessionCount int `json:"session_count" gorm:"default:1"`
|
// 月培训计划时据此关联(存量数据无值时回退同名扫描兜底)。
|
||||||
Location string `json:"location" gorm:"type:varchar(128);default:''"`
|
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
|
||||||
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
|
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
|
||||||
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
|
Category string `json:"category" gorm:"type:varchar(32);default:''"`
|
||||||
|
SessionCount int `json:"session_count" gorm:"default:1"`
|
||||||
|
Location string `json:"location" gorm:"type:varchar(128);default:''"`
|
||||||
|
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
|
||||||
|
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
|
||||||
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。
|
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。
|
||||||
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
|
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
|
||||||
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
|
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
|
||||||
@@ -591,8 +595,9 @@ type TrainingCourseLibrary struct {
|
|||||||
OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"`
|
OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"`
|
||||||
// Description 说明。
|
// Description 说明。
|
||||||
Description string `json:"description" gorm:"type:text;default:''"`
|
Description string `json:"description" gorm:"type:text;default:''"`
|
||||||
// SuitableMembers 适合人员(对应需求表「参加人员」,自由文本,如:财会人员)。
|
// SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接
|
||||||
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(255);default:''"`
|
// (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
|
||||||
|
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"`
|
||||||
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
|
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
|
||||||
Category string `json:"category" gorm:"type:varchar(64);default:''"`
|
Category string `json:"category" gorm:"type:varchar(64);default:''"`
|
||||||
// Type 类型(required 必修课/elective 选修课)。
|
// Type 类型(required 必修课/elective 选修课)。
|
||||||
|
|||||||
@@ -308,6 +308,9 @@ type UserInfo struct {
|
|||||||
Username string `json:"username" extensions:"x-agent"`
|
Username string `json:"username" extensions:"x-agent"`
|
||||||
Email string `json:"email" extensions:"x-agent"`
|
Email string `json:"email" extensions:"x-agent"`
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
|
// DisplayName 姓名/显示名。工号式 IdP 的 username 是工号,前端左下角等
|
||||||
|
// 位置展示姓名用;随 /auth/me、登录等返回 UserInfo 的接口一并下发。
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
TenantID uint64 `json:"tenant_id" extensions:"x-agent"`
|
TenantID uint64 `json:"tenant_id" extensions:"x-agent"`
|
||||||
IsActive bool `json:"is_active" extensions:"x-agent"`
|
IsActive bool `json:"is_active" extensions:"x-agent"`
|
||||||
CanAccessAllTenants bool `json:"can_access_all_tenants"`
|
CanAccessAllTenants bool `json:"can_access_all_tenants"`
|
||||||
@@ -324,6 +327,7 @@ func (u *User) ToUserInfo() *UserInfo {
|
|||||||
Username: u.Username,
|
Username: u.Username,
|
||||||
Email: u.Email,
|
Email: u.Email,
|
||||||
Avatar: u.Avatar,
|
Avatar: u.Avatar,
|
||||||
|
DisplayName: u.DisplayName,
|
||||||
TenantID: u.TenantID,
|
TenantID: u.TenantID,
|
||||||
IsActive: u.IsActive,
|
IsActive: u.IsActive,
|
||||||
CanAccessAllTenants: u.CanAccessAllTenants,
|
CanAccessAllTenants: u.CanAccessAllTenants,
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Migration: 000158_demand_library_course (rollback)
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Dropping tr_demands.library_course_id column...'; END $$;
|
||||||
|
|
||||||
|
ALTER TABLE tr_demands
|
||||||
|
DROP COLUMN IF EXISTS library_course_id;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- Migration: 000158_demand_library_course
|
||||||
|
-- 年度需求(tr_demands)增加所填课程的课程管理关联:填报/导入时按课程名称在
|
||||||
|
-- 课程管理精准查找,命中自动关联;未命中自动新增该课程(待核验,000157 流转),
|
||||||
|
-- 经理核验课程并确认需求自动转月培训计划后,发布课程前校验已签核完成。
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Adding tr_demands.library_course_id column...'; END $$;
|
||||||
|
|
||||||
|
ALTER TABLE tr_demands
|
||||||
|
ADD COLUMN IF NOT EXISTS library_course_id VARCHAR(36) NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN tr_demands.library_course_id IS 'Course library item id auto-matched by exact course name on demand save/import (000158); auto-created as verify-pending when not found';
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Migration: 000159_suitable_members_width (rollback)
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Restoring tr_course_library.suitable_members to VARCHAR(255)...'; END $$;
|
||||||
|
|
||||||
|
ALTER TABLE tr_course_library
|
||||||
|
ALTER COLUMN suitable_members TYPE VARCHAR(255);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- Migration: 000159_suitable_members_width
|
||||||
|
-- 「适合人员」改为部门多选口径(000159):存储归属部门名(「、」分隔,支持多选)
|
||||||
|
-- 或「全部」;单值/自由文本存量保持兼容(逗号/分号在匹配时归一)。拓宽列宽以
|
||||||
|
-- 容纳多部门名称拼接。
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Widening tr_course_library.suitable_members to VARCHAR(512)...'; END $$;
|
||||||
|
|
||||||
|
ALTER TABLE tr_course_library
|
||||||
|
ALTER COLUMN suitable_members TYPE VARCHAR(512);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN tr_course_library.suitable_members IS 'Suitable audience dept names joined by ''、'' (multi-select), or ''全部'' for all; legacy free text kept, delimiters normalized on matching';
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- Migration: 000160_tenant_seq_reserve_builtin_host (down)
|
||||||
|
-- 回滚到旧行为:序列回到 10000(与 000000 初始迁移一致)。仅当真实租户
|
||||||
|
-- 尚未占用 10000 时执行,否则保留现值(占用的 id 无法安全腾挪)。
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM tenants WHERE id = 10000) THEN
|
||||||
|
PERFORM setval('tenants_id_seq', 10000, false);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- Migration: 000160_tenant_seq_reserve_builtin_host
|
||||||
|
-- 租户序列与内置模型宿主租户(10000)避让。000000 初始迁移把 tenants_id_seq
|
||||||
|
-- 起点设为 10000,导致全新环境的第一个用户空间恰好占住保留的内置模型宿主
|
||||||
|
-- 租户 id(DefaultBuiltinModelTenantID=10000):SeedTenantDefaults 对该 id
|
||||||
|
-- 永不 seed(首用户空间没有任何默认库),且内置模型行(tenant_id=10000)
|
||||||
|
-- 的归属被真实空间占住。本迁移把序列推到 10001 之后:
|
||||||
|
-- 全新库(无租户行)→ 下一个租户 id 从 10001 开始,10000 永久保留;
|
||||||
|
-- 存量库 → 按现有 max(id) 连续续号,不受影响。
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000160] Realigning tenants_id_seq past reserved builtin-model host id 10000...'; END $$;
|
||||||
|
|
||||||
|
SELECT setval(
|
||||||
|
'tenants_id_seq',
|
||||||
|
GREATEST(COALESCE((SELECT MAX(id) FROM tenants), 0), 10001),
|
||||||
|
COALESCE((SELECT MAX(id) FROM tenants) IS NOT NULL, false)
|
||||||
|
);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Migration: 000161_org_roster_backfill (down)
|
||||||
|
-- 数据回填不可逆:回填行与此前人工/导入维护的员工档案无法区分(仅补空语义
|
||||||
|
-- 下老档案也可能被回填工号/部门),回滚不做删除,保留数据。
|
||||||
|
-- 如确需清理,请按 created_at 与迁移执行时间自行定位处理。
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000161] down is a no-op (backfilled roster rows are kept).'; END $$;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
-- Migration: 000161_org_roster_backfill
|
||||||
|
-- 存量平台成员一次性自动补入「组织架构」员工名册(需求:平台新增成员自动
|
||||||
|
-- 添加到组织架构并自动匹配对应部门)。此后新加入空间的成员由
|
||||||
|
-- tenantMemberService 的 ensureOrgRoster 挂钩实时入册(service/orgcenter.go
|
||||||
|
-- EnsureEmployeesForUsers),本迁移负责把迁移前就已加入空间的存量成员补齐:
|
||||||
|
-- - 工号 employee_no = 平台账号 users.username(与导入回填同约定);
|
||||||
|
-- - 部门按 Casdoor 同步字段自动匹配:users.dept_code 命中 org_depts.code
|
||||||
|
-- 优先,dept_name 命中 org_depts.name 兜底(小写去空格,各自 LATERAL 取
|
||||||
|
-- sort/created_at 序首行);匹配不到已维护部门时 dept_id 留空,由管理员
|
||||||
|
-- 在组织架构页手动调整;
|
||||||
|
-- - ON CONFLICT (tenant_id, user_id) DO NOTHING:已有档案(含软删行)一律
|
||||||
|
-- 不动,不覆盖任何人工/OA 同步字段,迁移幂等可重放。
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000161] Backfilling org_employees for existing tenant members...'; END $$;
|
||||||
|
|
||||||
|
INSERT INTO org_employees
|
||||||
|
(id, tenant_id, user_id, employee_no, dept_id, post, lecturer_rate, wecom_userid, status, created_at, updated_at)
|
||||||
|
SELECT
|
||||||
|
gen_random_uuid()::text,
|
||||||
|
tm.tenant_id,
|
||||||
|
tm.user_id,
|
||||||
|
u.username,
|
||||||
|
COALESCE(dc.id, dn.id, ''),
|
||||||
|
'',
|
||||||
|
0,
|
||||||
|
'',
|
||||||
|
'active',
|
||||||
|
NOW(),
|
||||||
|
NOW()
|
||||||
|
FROM tenant_members tm
|
||||||
|
JOIN users u
|
||||||
|
ON u.id = tm.user_id
|
||||||
|
AND u.is_active = TRUE
|
||||||
|
AND u.deleted_at IS NULL
|
||||||
|
-- 部门编号精确命中优先(dept_code 同步自 IdP,与 syncDepts 匹配口径一致)
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT d.id
|
||||||
|
FROM org_depts d
|
||||||
|
WHERE d.tenant_id = tm.tenant_id
|
||||||
|
AND d.deleted_at IS NULL
|
||||||
|
AND d.code <> ''
|
||||||
|
AND lower(btrim(d.code)) = lower(btrim(u.dept_code))
|
||||||
|
ORDER BY d.sort ASC, d.created_at ASC
|
||||||
|
LIMIT 1
|
||||||
|
) dc ON u.dept_code <> ''
|
||||||
|
-- 名称兜底:仅在编号未命中时参与,避免同名的编号部门抢占
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT d.id
|
||||||
|
FROM org_depts d
|
||||||
|
WHERE d.tenant_id = tm.tenant_id
|
||||||
|
AND d.deleted_at IS NULL
|
||||||
|
AND lower(btrim(d.name)) = lower(btrim(u.dept_name))
|
||||||
|
ORDER BY d.sort ASC, d.created_at ASC
|
||||||
|
LIMIT 1
|
||||||
|
) dn ON u.dept_name <> '' AND dc.id IS NULL
|
||||||
|
WHERE tm.status = 'active'
|
||||||
|
AND tm.deleted_at IS NULL
|
||||||
|
ON CONFLICT (tenant_id, user_id) DO NOTHING;
|
||||||
@@ -135,7 +135,11 @@ build_app_image() {
|
|||||||
|
|
||||||
# 获取版本信息
|
# 获取版本信息
|
||||||
get_version_info
|
get_version_info
|
||||||
|
|
||||||
|
# 离线快速通道兜底:Dockerfile.app 无条件 COPY docker/prebuilt/,目录缺失的
|
||||||
|
# 构建机会直接失败;占位空目录让没有预构建产物的宿主机走回原全量构建路径
|
||||||
|
mkdir -p docker/prebuilt
|
||||||
|
|
||||||
docker build \
|
docker build \
|
||||||
--platform $PLATFORM \
|
--platform $PLATFORM \
|
||||||
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
|
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
|
||||||
|
|||||||
Reference in new issue
Block a user