6 Commits
Author SHA1 Message Date
runny 8bd02e7c7e build(docker): 镜像构建新增离线预构建快速通道
deploy-hxtesting / build-and-deploy (push) Failing after 0s
- docker/prebuilt/ 携带宿主机交叉编译产物(Academy 二进制 + gojieba/yanyiwu
  运行时依赖)时,跳过 go mod download、license 归档、源码编译等联网步骤,
  直接装填预构建产物,适配网络受限构建环境
- 目录不入库(.gitignore 锚定 /docker/prebuilt/,与 artifacts/browserskill
  同口径):仅构建宿主机本地存在,上游在线构建走原路径不受影响
- .gitignore 另忽略本地 .cgo-sqlite/ 构建残留
2026-11-24 10:04:18 +08:00
runny 4112de0703 feat(onboarding): 注册引导确保企业培训默认库并补齐模型自动配置
空间引导(SeedTenantDefaults):
- 按 Source 标记独立幂等确保「企业培训(课件)/(题库)」两个系统默认库,
  CASDOOR/OIDC 注册、平台注册、管理员建空间统一触发;与培训域上传链路
  同源复用(不会重复建档),fail-open 不阻断注册主流程

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

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

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

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

No files matched your search

+5
View File
@@ -73,5 +73,10 @@ miniprogram/project.private.config.json
# Locally built BrowserSkill runtime and extension bundles # Locally built BrowserSkill runtime and extension bundles
/artifacts/browserskill/ /artifacts/browserskill/
# Offline Docker build fast-path artifacts (prebuilt binary + runtime deps,
# carried on the build host only — never committed, see docker/Dockerfile.app)
/docker/prebuilt/
# Local DuckDB extension extraction scratch dir (training template debugging) # Local DuckDB extension extraction scratch dir (training template debugging)
tmp-extract-duckdb/ tmp-extract-duckdb/
.cgo-sqlite/
+22 -3
View File
@@ -83,10 +83,20 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
# so that module's go.mod must exist before `go mod download`. # so that module's go.mod must exist before `go mod download`.
COPY go.mod go.sum ./ COPY go.mod go.sum ./
COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod COPY third_party/anydoc-go/go.mod third_party/anydoc-go/go.mod
# 离线快速通道(网络受限环境):docker/prebuilt/ 携带宿主机交叉编译的产物时,
# 跳过 go mod download 等联网步骤,直接装填预构建二进制与 gojieba 运行时依赖。
# 目录不入库(与 artifacts/browserskill 同口径),上游构建走下方原有路径不受影响。
COPY docker/prebuilt/ /app/prebuilt/
# 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖, # 模块缓存挂载复用(下载产物不进镜像层;yanyiwu 目录是 gojieba 运行时依赖,
# 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载) # 复制到层内固定路径供后续 COPY,避免依赖已被卸载的缓存挂载)
RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/ if [ -f /app/prebuilt/Academy ]; then \
mkdir -p /go/pkg/mod/github.com/yanyiwu && \
tar -xzf /app/prebuilt/yanyiwu.tar.gz -C /go/pkg/mod/github.com/yanyiwu && \
cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
else \
go mod download && cp -r /go/pkg/mod/github.com/yanyiwu/ /app/yanyiwu-mod/; \
fi
COPY cmd/download cmd/download COPY cmd/download cmd/download
# DuckDB extensions (spatial/excel): prefer a local seed tarball exported from # DuckDB extensions (spatial/excel): prefer a local seed tarball exported from
# a previously built image (artifacts/duckdb_extensions/seed.tar) — # a previously built image (artifacts/duckdb_extensions/seed.tar) —
@@ -100,7 +110,13 @@ RUN if [ -s /tmp/duckdb-seed.tar ]; then \
go run cmd/download/duckdb/duckdb.go; \ go run cmd/download/duckdb/duckdb.go; \
fi fi
COPY . . COPY . .
RUN bash ./scripts/copy-licenses.sh /license-bundle # license 归档属发布输入(联网逐模块校验),离线快速通道下跳过,不影响运行时功能
RUN if [ -f /app/prebuilt/Academy ]; then \
echo "==> Offline fast-path: skip license bundle"; \
mkdir -p /license-bundle/licenses/sources; \
else \
bash ./scripts/copy-licenses.sh /license-bundle; \
fi
# Get version and commit info for build injection # Get version and commit info for build injection
ARG VERSION_ARG ARG VERSION_ARG
@@ -163,7 +179,10 @@ RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod \
objcopy --remove-section "$s" "$a" || true; \ objcopy --remove-section "$s" "$a" || true; \
done; \ done; \
done; \ done; \
if [ "$WITH_ANYDOC" = "1" ]; then \ if [ -f /app/prebuilt/Academy ]; then \
echo "==> Using prebuilt binary from docker/prebuilt/"; \
cp /app/prebuilt/Academy /app/Academy; \
elif [ "$WITH_ANYDOC" = "1" ]; then \
make build-prod GO_BUILD_TAGS=anydoc; \ make build-prod GO_BUILD_TAGS=anydoc; \
else \ else \
make build-prod; \ make build-prod; \
+5 -3
View File
@@ -43,9 +43,11 @@
| 项 | 值 | | 项 | 值 |
| --- | --- | | --- | --- |
| 生产服入口 | http://192.168.100.230:8802(域名绑定待 DNS 管理员登记后更新) | | 生产服入口 | **https://kb.well-trust.com**(ai30 nginx 443 反代 8802;备选直连 http://192.168.100.230:8802) |
| 测试服入口 | **https://kbt.well-trust.com**(同一证书/vhost 反代 hxtesting 8801;备选 http://192.168.100.192:8801) |
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy | | 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
| 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) | | 部署机 runner | `ssh ai30 'systemctl --user status gitea-runner'`(inspur,Linger=yes 开机自启) |
| 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 `http://192.168.100.230:8802/api/v1/auth/oidc/callback`(域名定稿后同步追加域名回调);client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) | | 认证 | 正式 Casdoor `auth.well-trust.com`;回调登记 IP 与 https://kb.well-trust.com 两路 + localhost:5173;client 凭据存 Mac `~/dev-tools/aido-oidc-prod.txt`(600) |
| Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行前快照) | | Casdoor 改库备份 | ai30 shared-postgres `casdoor_db.application_bak_20261119`(注册应用行)、`application_bak_20261120`(域名回调更新前) |
| 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) | | 数据落位 | ai30 Docker 数据根 `/data/lib/docker`(/data 卷,987G 可用) |
| 域名/证书 | kb+kbt SAN 一张(`/data/ai-platform/.certbot/config/live/kb.well-trust.com/`),DNS A 记录与 TXT 验证均走阿里 API(凭据 `aliyun-welltrust.ini`)自动完成,续期 dns-aliyun 全自动;vhost=`/etc/nginx/conf.d/kb-academy.conf`(预写件 `/data/ai-platform/kb-academy-nginx.conf`,装载需一次 sudo) |
+2 -2
View File
@@ -47,8 +47,8 @@
| 项 | 值 | | 项 | 值 |
| --- | --- | | --- | --- |
| 测试服入口 | http://192.168.100.192:8801(FRONTEND_PORT=8801,登记册 88xx 平台段) | | 测试服入口 | **https://kbt.well-trust.com**(ai30 nginx 反代;备选 http://192.168.100.192:8801,FRONTEND_PORT=8801,登记册 88xx 平台段) |
| 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy | | 代码仓库 | http://192.168.100.230:3000/szsy_organization/ai_academy |
| 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) | | 流水线 | 仓库 → 工作流 tab(workflow 文件:`.gitea/workflows/deploy-hxtesting.yml`) |
| 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 与本地 5173) | | 认证 | 测试 Casdoor `autht.well-trust.com`(应用名 ai-academy,回调登记 8801 / https://kbt.well-trust.com 与本地 5173) |
| 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) | | 本地开发 | `make dev-start` → `./scripts/dev.sh app` → `./scripts/dev.sh frontend`(前端 5173 代理后端) |
+3
View File
@@ -118,6 +118,8 @@ export interface UserInfo {
username: string username: string
email: string email: string
avatar?: string avatar?: string
// 姓名/显示名(工号式账号的 username 是工号,界面展示姓名用;未设置为空串)
display_name?: string
tenant_id: string tenant_id: string
can_access_all_tenants?: boolean can_access_all_tenants?: boolean
preferences?: UserPreferences preferences?: UserPreferences
@@ -158,6 +160,7 @@ export function userInfoFromApi(
username: u?.username || '', username: u?.username || '',
email: u?.email || '', email: u?.email || '',
avatar: u?.avatar, avatar: u?.avatar,
display_name: u?.display_name || '',
tenant_id: String(tid) || '', tenant_id: String(tid) || '',
can_access_all_tenants: u?.can_access_all_tenants === true, can_access_all_tenants: u?.can_access_all_tenants === true,
is_system_admin: u?.is_system_admin === true, is_system_admin: u?.is_system_admin === true,
+3 -1
View File
@@ -162,6 +162,8 @@ export interface TrainingDemand {
dept_id: string dept_id: string
submitter_id: string submitter_id: string
course_name: string course_name: string
/** 需求所填课程自动匹配的课程管理条目 id(000158:填报/导入时按名称精准匹配,未命中自动新增待核验课程) */
library_course_id?: string
/** 厂区(模板列:厂区,如 三厂) */ /** 厂区(模板列:厂区,如 三厂) */
plant: string plant: string
/** 培训分类(模板列:分类,如 知识/技能/安全) */ /** 培训分类(模板列:分类,如 知识/技能/安全) */
@@ -185,7 +187,7 @@ export interface TrainingDemand {
check_status: 'pending' | 'passed' | 'fixed' check_status: 'pending' | 'passed' | 'fixed'
check_msg: string check_msg: string
status: string status: string
/** 联查展示字段:部门名称/讲师姓名/创建人姓名(提报人,联查 users 只读) */ /** 部门名称(列表联查 org_depts 只读;导入载荷另携带 Excel「部门」列原始值,000158 后端据此做导入人部门归属校验) */
dept_name?: string dept_name?: string
lecturer_name?: string lecturer_name?: string
submitter_name?: string submitter_name?: string
+15 -7
View File
@@ -8,12 +8,12 @@
<span v-else class="avatar-placeholder">{{ userInitial }}</span> <span v-else class="avatar-placeholder">{{ userInitial }}</span>
</div> </div>
<div v-if="!showCollapsedLayout" class="user-info"> <div v-if="!showCollapsedLayout" class="user-info">
<!-- 多空间 / superuser:首行空间名,次行 username · 角色。单空间:昵称 + 邮箱。 --> <!-- 多空间 / superuser:首行空间名,次行 姓名(未设置回落账号) · 角色。单空间:账号 + 姓名(未设置回落邮箱)。 -->
<template v-if="showTenantIdentityLine"> <template v-if="showTenantIdentityLine">
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div> <div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
<div class="user-tenant-meta"> <div class="user-tenant-meta">
<span v-if="userName && userName !== activeTenantName" class="user-tenant-meta-name">{{ userName }}</span> <span v-if="userDisplayLabel && userDisplayLabel !== activeTenantName" class="user-tenant-meta-name">{{ userDisplayLabel }}</span>
<span v-if="(userName && userName !== activeTenantName) && currentRoleLabel" <span v-if="(userDisplayLabel && userDisplayLabel !== activeTenantName) && currentRoleLabel"
class="user-tenant-meta-sep">·</span> class="user-tenant-meta-sep">·</span>
<t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" /> <t-icon v-if="currentRoleIcon" :name="currentRoleIcon" size="12px" class="user-tenant-meta-icon" />
<span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span> <span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span>
@@ -21,7 +21,7 @@
</template> </template>
<template v-else> <template v-else>
<div class="user-name">{{ userName }}</div> <div class="user-name">{{ userName }}</div>
<div class="user-email">{{ userEmail }}</div> <div class="user-email">{{ userDisplayName }}</div>
</template> </template>
</div> </div>
</div> </div>
@@ -67,7 +67,7 @@
</button> </button>
</t-tooltip> </t-tooltip>
</div> </div>
<span v-if="userEmail" class="dropdown-user-email">{{ userEmail }}</span> <span v-if="userDisplayName" class="dropdown-user-email">{{ userDisplayName }}</span>
</div> </div>
</div> </div>
@@ -198,6 +198,7 @@ const menuVisible = ref(false)
const userInfo = computed(() => ({ const userInfo = computed(() => ({
username: authStore.user?.username || t('common.defaultUser'), username: authStore.user?.username || t('common.defaultUser'),
email: authStore.user?.email || 'user@example.com', email: authStore.user?.email || 'user@example.com',
displayName: authStore.user?.display_name || '',
avatar: authStore.user?.avatar || '', avatar: authStore.user?.avatar || '',
})) }))
@@ -205,9 +206,16 @@ const userName = computed(() => userInfo.value.username)
const userEmail = computed(() => userInfo.value.email) const userEmail = computed(() => userInfo.value.email)
const userAvatar = computed(() => userInfo.value.avatar) const userAvatar = computed(() => userInfo.value.avatar)
// 用户名首字母(用于无头像时显示) // 侧栏第二行:工号式账号的 username 是工号,优先展示姓名;未设置姓名时回落邮箱
const userDisplayName = computed(() => userInfo.value.displayName || userInfo.value.email)
// 多空间身份行的姓名标签:优先姓名,未设置姓名时回落账号(工号/用户名)
const userDisplayLabel = computed(() => userInfo.value.displayName || userInfo.value.username)
// 用户名首字母(用于无头像时显示):优先取姓名首字(如「刘义亮」→「刘」),
// 未设置姓名时回落账号首字符
const userInitial = computed(() => { const userInitial = computed(() => {
return userName.value.charAt(0).toUpperCase() return userDisplayLabel.value.charAt(0).toUpperCase()
}) })
// 切换菜单显示 // 切换菜单显示
@@ -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 = [];
@@ -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')
+14 -24
View File
@@ -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)
} }
// ---- 学习进度心跳 ---- // ---- 学习进度心跳 ----
+14 -3
View File
@@ -116,10 +116,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 +215,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(),
@@ -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
} }
@@ -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 兜底)两条路径。
+9 -2
View File
@@ -119,9 +119,16 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
// 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default // 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default
// 优先,否则该类型第一个 active)。fail-open:解析不到保持为空, // 优先,否则该类型第一个 active)。fail-open:解析不到保持为空,
// 运行时的 "chat model is not configured" 报错行为与现状一致。 // 运行时的 "chat model is not configured" 报错行为与现状一致。
if strings.TrimSpace(agent.Config.ModelID) == "" && s.modelService != nil { // ReRank 同口径兜底:无可用重排模型时保持为空(按需运行,不阻断)。
if s.modelService != nil &&
(strings.TrimSpace(agent.Config.ModelID) == "" || strings.TrimSpace(agent.Config.RerankModelID) == "") {
if models, err := s.modelService.ListModels(ctx); err == nil { if models, err := s.modelService.ListModels(ctx); err == nil {
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA) if strings.TrimSpace(agent.Config.ModelID) == "" {
agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
}
if strings.TrimSpace(agent.Config.RerankModelID) == "" {
agent.Config.RerankModelID = PickDefaultModelID(models, types.ModelTypeRerank)
}
} else { } else {
logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err) logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err)
} }
@@ -20,7 +20,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:任何一步失败只记日志,绝不阻断注册/建租户主流程;
// 且整体幂等——租户下已存在同名入门库时直接跳过。 // 且整体幂等——租户下已存在同名入门库时直接跳过。
@@ -124,6 +126,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)
@@ -184,6 +192,50 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant
} }
} }
// 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
+94 -4
View File
@@ -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
+121 -15
View File
@@ -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) {
+174 -50
View File
@@ -32,12 +32,41 @@ func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotifi
return &Handler{svc: svc, pusher: pusher} return &Handler{svc: svc, pusher: pusher}
} }
// trainingTenantContextKey 培训域解析后的数据空间租户 id(000160):由
// TrainingTenantResolution 中间件写入,callerTenantID 优先读取。
const trainingTenantContextKey = "training_tenant_id"
// TrainingTenantResolution 企业培训数据空间解析中间件(000160):认证守卫之后
// 执行,按「当前空间有培训档案优先,否则回退员工档案所在空间」解析培训域实际
// 读写的租户并写入上下文;本组所有 handler 的 callerTenantID 均取解析值 ——
// 同一组织的人员切换到任意工作区,都能看到并参与其档案所属组织的企业培训。
func (h *Handler) TrainingTenantResolution() gin.HandlerFunc {
return func(c *gin.Context) {
active := c.GetUint64(types.TenantIDContextKey.String())
userID := callerUserID(c)
if active != 0 && userID != "" {
if resolved, err := h.svc.ResolveTrainingTenant(c.Request.Context(), active, userID); err == nil && resolved != 0 {
c.Set(trainingTenantContextKey, resolved)
// 执行租户随培训空间同步回落(000160):课件文件流(GetKnowledgeFile)、
// 培训知识库 ensure 等按 ctx 租户读写的服务链路才落在档案所在空间;
// caller 身份保持当前工作区不变,授权口径不受影响。
c.Request = c.Request.WithContext(types.WithExecutionTenant(c.Request.Context(), resolved))
}
}
c.Next()
}
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 请求上下文辅助 // 请求上下文辅助
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// callerTenantID reads the tenant id injected by the auth middleware. // callerTenantID reads the tenant id injected by the auth middleware, or the
// training-resolved tenant (000160) when the route group middleware resolved one.
func callerTenantID(c *gin.Context) uint64 { func callerTenantID(c *gin.Context) uint64 {
if v := c.GetUint64(trainingTenantContextKey); v != 0 {
return v
}
return c.GetUint64(types.TenantIDContextKey.String()) return c.GetUint64(types.TenantIDContextKey.String())
} }
@@ -400,6 +429,18 @@ func (h *Handler) Me(c *gin.Context) {
_ = c.Error(err) _ = c.Error(err)
return return
} }
// 联查部门名(000160):员工档案只存 dept_id,前端课程目录按部门名匹配
// 「适合人员」、表单默认值展示均需要名称;档案无部门时保持空串。
if member.DeptID != "" {
if depts, err := h.svc.ListDepts(ctx, callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
member.DeptName = d.Name
break
}
}
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member}) c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
} }
@@ -436,9 +477,12 @@ func (h *Handler) ListDemandYears(c *gin.Context) {
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/ // 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。 // 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
type saveDemandRequest struct { type saveDemandRequest struct {
ID string `json:"id"` ID string `json:"id"`
Year int `json:"year"` Year int `json:"year"`
DeptID string `json:"dept_id"` DeptID string `json:"dept_id"`
// DeptName Excel「部门」列原始值(仅批量导入部门归属校验用,000158:全部行
// 必须为导入人本人部门;在线提报不传,服务端强制按提报人部门落库)。
DeptName string `json:"dept_name"`
CourseName string `json:"course_name" binding:"required"` CourseName string `json:"course_name" binding:"required"`
Plant string `json:"plant"` Plant string `json:"plant"`
Category string `json:"category"` Category string `json:"category"`
@@ -504,14 +548,23 @@ func (h *Handler) SaveDemand(c *gin.Context) {
return return
} }
} }
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。 // 部门口径(000158):所属部门必须为填报人本人部门——新建强制按提报人所在
deptID := trimSpace(req.DeptID) // 部门(org_employees.dept_id)落库,忽略请求值防绕过;编辑保留原部门(人事
if deptID == "" { // 代改也不覆盖归属)。提报人无部门档案时阻断,先由人事在组织中心维护。
if existing != nil { var deptID string
deptID = existing.DeptID if existing != nil {
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil { deptID = existing.DeptID
deptID = member.DeptID } else {
member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
} }
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再提报"))
return
}
deptID = member.DeptID
} }
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{ demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
ID: req.ID, Year: req.Year, DeptID: deptID, ID: req.ID, Year: req.Year, DeptID: deptID,
@@ -575,6 +628,9 @@ func (h *Handler) ListPosts(c *gin.Context) {
} }
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。 // ImportDemands POST /training/demands/import — 调研表在线化批量导入。
// 部门口径(000158):全部行必须为导入人本人部门(org_employees.dept_id,全员
// 严格,人事也不例外);部门列留空视为默认导入人部门,其余任一行不符即整批
// 拒绝。导入人无部门档案时阻断,先由人事在组织中心维护。
func (h *Handler) ImportDemands(c *gin.Context) { func (h *Handler) ImportDemands(c *gin.Context) {
ctx := c.Request.Context() ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) { if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
@@ -587,10 +643,47 @@ func (h *Handler) ImportDemands(c *gin.Context) {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error())) _ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return return
} }
tenantID, userID := callerTenantID(c), callerUserID(c)
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
if err != nil {
_ = c.Error(err)
return
}
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再导入"))
return
}
// 整批部门预检:任一行部门与导入人不符即拒绝,不做部分导入。
// 通过口径:行部门 id 与本人一致,或部门列全空(默认导入人部门)。
myDeptName := h.deptNameOf(ctx, tenantID, member.DeptID)
violations := make([]string, 0, len(req.Demands))
for i, item := range req.Demands {
deptID, deptName := trimSpace(item.DeptID), trimSpace(item.DeptName)
if deptID == "" && deptName == "" {
continue
}
if deptID == member.DeptID {
continue
}
if deptName == "" {
deptName = h.deptNameOf(ctx, tenantID, deptID)
}
if deptName == "" {
deptName = deptID
}
violations = append(violations, fmt.Sprintf("第%d行(%s)", i+1, deptName))
}
if len(violations) > 0 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf(
"导入失败:第%s行部门与您所在部门(%s)不一致,仅可导入本人部门的需求表",
strings.Join(violations, "、"), myDeptName)))
return
}
demands := make([]*types.TrainingDemand, 0, len(req.Demands)) demands := make([]*types.TrainingDemand, 0, len(req.Demands))
for _, item := range req.Demands { for _, item := range req.Demands {
demands = append(demands, &types.TrainingDemand{ demands = append(demands, &types.TrainingDemand{
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName, // 部门强制为导入人本人部门:部门列留空的行在此默认,其余已通过预检。
Year: item.Year, DeptID: member.DeptID, CourseName: item.CourseName,
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount, Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID, Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType), LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
@@ -598,16 +691,34 @@ func (h *Handler) ImportDemands(c *gin.Context) {
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark, PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
}) })
} }
result, err := h.svc.ImportDemands(ctx, callerTenantID(c), demands, callerUserID(c)) result, coursesCreated, err := h.svc.ImportDemands(ctx, tenantID, demands, userID)
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
return return
} }
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。 // 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands) h.syncDemandLecturerToLibrary(ctx, tenantID, userID, demands)
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。 // 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands) notified := h.notifyDemandVerify(ctx, tenantID, demands)
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}}) c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"imported": len(result), "notified": notified, "courses_created": coursesCreated}})
}
// deptNameOf 部门 id → 名称(导入报错文案用;查不到时回退展示 id)。
func (h *Handler) deptNameOf(ctx context.Context, tenantID uint64, deptID string) string {
if trimSpace(deptID) == "" {
return ""
}
depts, err := h.svc.ListDepts(ctx, tenantID)
if err != nil {
return deptID
}
for _, d := range depts {
if d != nil && d.ID == deptID {
return d.Name
}
}
return deptID
} }
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄): // demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
@@ -681,10 +792,13 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
PostScope: demand.PostScope, PostScope: demand.PostScope,
} }
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源; // 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息), // 课程管理关联(000158):需求填报/导入时已按名称精准匹配并回填
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。 // library_course_id(未命中自动新增待核验课程),此处直接采用;存量需求
// 无值时回退课程管理同名扫描兜底(计划侧自动带出并锁定课程信息)。
course.SourceDemandID = demand.ID course.SourceDemandID = demand.ID
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil { if trimSpace(demand.LibraryCourseID) != "" {
course.LibraryCourseID = demand.LibraryCourseID
} else if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
for _, item := range libItems { for _, item := range libItems {
if item != nil && item.Name == demand.CourseName { if item != nil && item.Name == demand.CourseName {
course.LibraryCourseID = item.ID course.LibraryCourseID = item.ID
@@ -901,47 +1015,75 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
} }
} }
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存) // syncDemandLecturerToLibrary 需求课程信息回写课程管理(000156/000161):需求
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后 // (导入/在线保存/编辑)所关联的课程管理条目——优先 demand.library_course_id
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。 // (000158 自动匹配),无值回退同名匹配——讲师与条目不一致时以需求为准更新;
// 000161 扩展:分类/适合人员(需求侧改后)同样回写。SaveCourseLibraryItem 的
// 编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须重新签核。
// 同批同名取首条。fail-open:失败仅记日志不阻断保存/导入。
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) { func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
byID := map[string]*types.TrainingDemand{}
byName := map[string]*types.TrainingDemand{} byName := map[string]*types.TrainingDemand{}
for _, d := range demands { for _, d := range demands {
if d == nil || trimSpace(d.CourseName) == "" { if d == nil || trimSpace(d.CourseName) == "" {
continue continue
} }
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" { if id := trimSpace(d.LibraryCourseID); id != "" {
if _, ok := byID[id]; !ok {
byID[id] = d
}
continue continue
} }
if _, ok := byName[d.CourseName]; !ok { if _, ok := byName[d.CourseName]; !ok {
byName[d.CourseName] = d byName[d.CourseName] = d
} }
} }
if len(byName) == 0 { if len(byID) == 0 && len(byName) == 0 {
return return
} }
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}) items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil { if err != nil {
logger.Error(ctx, "Failed to list course library for lecturer sync", err) logger.Error(ctx, "Failed to list course library for demand sync", err)
return return
} }
for _, item := range items { for _, item := range items {
if item == nil { if item == nil {
continue continue
} }
d, ok := byName[item.Name] d, ok := byID[item.ID]
if !ok {
d, ok = byName[item.Name]
}
if !ok { if !ok {
continue continue
} }
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal) lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt { if lecturerID != "" {
lecturerExt = ""
}
hasLecturer := lecturerID != "" || lecturerExt != ""
category, suitable := trimSpace(d.Category), trimSpace(d.PostScope)
// 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止
// 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。
changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) ||
(category != "" && item.Category != category) ||
(suitable != "" && item.SuitableMembers != suitable)
if !changed {
continue continue
} }
updated := *item updated := *item
updated.LecturerID = lecturerID if hasLecturer {
updated.LecturerExternal = lecturerExt updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
}
if category != "" {
updated.Category = category
}
if suitable != "" {
updated.SuitableMembers = suitable
}
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil { if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync demand lecturer to course library", err) logger.Error(ctx, "Failed to sync demand course info to course library", err)
continue continue
} }
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。 // 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
@@ -1221,26 +1363,8 @@ func (h *Handler) PublishCourse(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) { if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return return
} }
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。 // 发布前置校验(线上课件/线下讲师等)统一收口在 service PublishCourse:
course, err := h.svc.GetCourse(ctx, callerTenantID(c), c.Param("id")) // 线上课件认计划自带或课程管理自带课件,考题非必填。
if err != nil {
_ = c.Error(err)
return
}
if course.Mode == "online" {
materials, err := h.svc.ListMaterials(ctx, callerTenantID(c), course.ID)
if err != nil {
_ = c.Error(err)
return
}
if len(materials) == 0 {
_ = c.Error(errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)"))
return
}
} else if trimSpace(course.LecturerID) == "" {
_ = c.Error(errors.NewBadRequestError("线下课程发布前需先指定讲师"))
return
}
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c)) published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
if err != nil { if err != nil {
_ = c.Error(err) _ = c.Error(err)
+23 -1
View File
@@ -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)
}
+4 -1
View File
@@ -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)
+19 -1
View File
@@ -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 需求提报表单下拉数据源(讲师/岗位)。
+17 -12
View File
@@ -363,16 +363,20 @@ type TrainingDemand struct {
TenantID uint64 `json:"tenant_id" gorm:"not null;index"` TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Year int `json:"year" gorm:"not null;index"` Year int `json:"year" gorm:"not null;index"`
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。 // Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
Code string `json:"code" gorm:"type:varchar(32);default:''"` Code string `json:"code" gorm:"type:varchar(32);default:''"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"` DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"` SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"` CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
Plant string `json:"plant" gorm:"type:varchar(64);default:''"` // LibraryCourseID 需求所填课程自动匹配的课程管理条目 id(000158):填报/导入时
Category string `json:"category" gorm:"type:varchar(32);default:''"` // 按课程名称精准查找,命中回填;未命中自动新增该课程(待核验)后回填,确认转
SessionCount int `json:"session_count" gorm:"default:1"` // 月培训计划时据此关联(存量数据无值时回退同名扫描兜底)。
Location string `json:"location" gorm:"type:varchar(128);default:''"` LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"` Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"` Category string `json:"category" gorm:"type:varchar(32);default:''"`
SessionCount int `json:"session_count" gorm:"default:1"`
Location string `json:"location" gorm:"type:varchar(128);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。 // LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"` LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。 // TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
@@ -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 选修课)。
+4
View File
@@ -308,6 +308,9 @@ type UserInfo struct {
Username string `json:"username" extensions:"x-agent"` Username string `json:"username" extensions:"x-agent"`
Email string `json:"email" extensions:"x-agent"` Email string `json:"email" extensions:"x-agent"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
// DisplayName 姓名/显示名。工号式 IdP 的 username 是工号,前端左下角等
// 位置展示姓名用;随 /auth/me、登录等返回 UserInfo 的接口一并下发。
DisplayName string `json:"display_name"`
TenantID uint64 `json:"tenant_id" extensions:"x-agent"` TenantID uint64 `json:"tenant_id" extensions:"x-agent"`
IsActive bool `json:"is_active" extensions:"x-agent"` IsActive bool `json:"is_active" extensions:"x-agent"`
CanAccessAllTenants bool `json:"can_access_all_tenants"` CanAccessAllTenants bool `json:"can_access_all_tenants"`
@@ -324,6 +327,7 @@ func (u *User) ToUserInfo() *UserInfo {
Username: u.Username, Username: u.Username,
Email: u.Email, Email: u.Email,
Avatar: u.Avatar, Avatar: u.Avatar,
DisplayName: u.DisplayName,
TenantID: u.TenantID, TenantID: u.TenantID,
IsActive: u.IsActive, IsActive: u.IsActive,
CanAccessAllTenants: u.CanAccessAllTenants, CanAccessAllTenants: u.CanAccessAllTenants,
@@ -0,0 +1,6 @@
-- Migration: 000158_demand_library_course (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Dropping tr_demands.library_course_id column...'; END $$;
ALTER TABLE tr_demands
DROP COLUMN IF EXISTS library_course_id;
@@ -0,0 +1,11 @@
-- Migration: 000158_demand_library_course
-- 年度需求(tr_demands)增加所填课程的课程管理关联:填报/导入时按课程名称在
-- 课程管理精准查找,命中自动关联;未命中自动新增该课程(待核验,000157 流转),
-- 经理核验课程并确认需求自动转月培训计划后,发布课程前校验已签核完成。
DO $$ BEGIN RAISE NOTICE '[Migration 000158] Adding tr_demands.library_course_id column...'; END $$;
ALTER TABLE tr_demands
ADD COLUMN IF NOT EXISTS library_course_id VARCHAR(36) NOT NULL DEFAULT '';
COMMENT ON COLUMN tr_demands.library_course_id IS 'Course library item id auto-matched by exact course name on demand save/import (000158); auto-created as verify-pending when not found';
@@ -0,0 +1,6 @@
-- Migration: 000159_suitable_members_width (rollback)
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Restoring tr_course_library.suitable_members to VARCHAR(255)...'; END $$;
ALTER TABLE tr_course_library
ALTER COLUMN suitable_members TYPE VARCHAR(255);
@@ -0,0 +1,11 @@
-- Migration: 000159_suitable_members_width
-- 「适合人员」改为部门多选口径(000159):存储归属部门名(「、」分隔,支持多选)
-- 或「全部」;单值/自由文本存量保持兼容(逗号/分号在匹配时归一)。拓宽列宽以
-- 容纳多部门名称拼接。
DO $$ BEGIN RAISE NOTICE '[Migration 000159] Widening tr_course_library.suitable_members to VARCHAR(512)...'; END $$;
ALTER TABLE tr_course_library
ALTER COLUMN suitable_members TYPE VARCHAR(512);
COMMENT ON COLUMN tr_course_library.suitable_members IS 'Suitable audience dept names joined by ''、'' (multi-select), or ''全部'' for all; legacy free text kept, delimiters normalized on matching';