This commit is contained in:
commit
3a20abc492
30 files changed
+1150
-143
No files matched your search
@@ -4,8 +4,14 @@ tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -tags \"${GO_BUILD_TAGS}\" -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server"
|
||||
# 产物带 .exe 后缀:Windows 下 air 经 PowerShell 启动二进制,不识别无后缀文件
|
||||
# (Unix 对扩展名不敏感,同一 bin 路径两端通用)。
|
||||
bin = "./tmp/main.exe"
|
||||
# 构建收敛到 scripts/air_build.sh:Windows 下 air 经 PowerShell 执行 cmd,
|
||||
# 不能做 bash 命令替换/直接执行 .sh,内联 $(./scripts/get_version.sh ...) 会失败;
|
||||
# macOS/Linux 经 /bin/sh -c 调 bash 同样可用,构建口径全平台一致
|
||||
# (GO_BUILD_TAGS/CGO_CFLAGS 环境变量由 scripts/dev.sh 导入,脚本内继承)。
|
||||
cmd = "bash ./scripts/air_build.sh"
|
||||
delay = 1000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs", "logs", "data", "Academy-Chrome-Extension", "Formula", "dataset", "docreader", "docker", "llm_debug", "web", "mcp-server", "misc", "scripts", "dist", "client", "helm", "website-docs"]
|
||||
exclude_file = []
|
||||
|
||||
@@ -185,9 +185,11 @@ export interface TrainingDemand {
|
||||
check_status: 'pending' | 'passed' | 'fixed'
|
||||
check_msg: string
|
||||
status: string
|
||||
/** 联查展示字段:部门名称/讲师姓名 */
|
||||
/** 联查展示字段:部门名称/讲师姓名/创建人姓名(提报人,联查 users 只读) */
|
||||
dept_name?: string
|
||||
lecturer_name?: string
|
||||
submitter_name?: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface TrainingAnnualPlan {
|
||||
@@ -460,6 +462,8 @@ export interface TrainingLibraryCourse {
|
||||
clear_file?: boolean
|
||||
/** 讲师姓名(联查 users 只读) */
|
||||
lecturer_name?: string
|
||||
/** 创建人姓名(联查 users 只读;导入/新增时落 creator_id 后带出) */
|
||||
creator_name?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@@ -1270,6 +1274,8 @@ export const markNotificationsRead = () =>
|
||||
post<{ success: boolean }>(`${base}/notifications/read`, {})
|
||||
|
||||
// BroadcastNotification 培训运营向指定平台用户批量推送站内通知(收集下年度计划等场景)。
|
||||
// link_url 传前端 origin:demand_collect 场景企微消息尾部由后端拼
|
||||
// 「下载教育训练需求表模板(签名直链)+ 查看更多详情」两行链接。
|
||||
export const broadcastTrainingNotification = (payload: {
|
||||
user_ids: string[]
|
||||
scene?: string
|
||||
@@ -1277,9 +1283,45 @@ export const broadcastTrainingNotification = (payload: {
|
||||
content?: string
|
||||
ref_type?: string
|
||||
ref_id?: string
|
||||
link_url?: string
|
||||
}) =>
|
||||
post<{ success: boolean; data: { sent: number } }>(`${base}/notifications/broadcast`, payload)
|
||||
|
||||
// ---- 年培训计划收集推送文案(配置中心「提醒推送文案」卡可配) ----
|
||||
|
||||
/** notify_text_templates 规则键(与后端 ruleKeyNotifyTextTemplates 一致)。 */
|
||||
export const NOTIFY_TEXT_TEMPLATES_RULE_KEY = 'notify_text_templates'
|
||||
|
||||
// [2026-11 需求] 收集推送默认文案(与后端 defaultDemandCollect* 逐字一致):
|
||||
// 配置中心 demand_collect_title/demand_collect_content 可编辑,{year} 在
|
||||
// 收集弹窗预填与后端广播回落渲染时替换为收集年度(下一年)。
|
||||
export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集'
|
||||
export const DEFAULT_DEMAND_COLLECT_CONTENT =
|
||||
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
|
||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||
|
||||
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
|
||||
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
|
||||
export async function fetchDemandCollectText(): Promise<{ title: string; content: string }> {
|
||||
let title = DEFAULT_DEMAND_COLLECT_TITLE
|
||||
let content = DEFAULT_DEMAND_COLLECT_CONTENT
|
||||
try {
|
||||
const res = await listRuleConfigs()
|
||||
const saved = (unwrap<TrainingRuleConfig[]>(res) || []).find(
|
||||
(c) => c.rule_key === NOTIFY_TEXT_TEMPLATES_RULE_KEY,
|
||||
)?.rule_value
|
||||
if (typeof saved?.demand_collect_title === 'string' && saved.demand_collect_title.trim()) {
|
||||
title = saved.demand_collect_title
|
||||
}
|
||||
if (typeof saved?.demand_collect_content === 'string' && saved.demand_collect_content.trim()) {
|
||||
content = saved.demand_collect_content
|
||||
}
|
||||
} catch {
|
||||
// 拉取失败回退内置默认,收集弹窗预填不受影响
|
||||
}
|
||||
return { title, content }
|
||||
}
|
||||
|
||||
// ---- 推送管理(2026-11 推学员/推讲师需求,配置中心展示) ----
|
||||
|
||||
// TrainingPushLog 推送逐人明细行(镜像 internal/types.TrainingPushLog)。
|
||||
|
||||
@@ -70,6 +70,8 @@
|
||||
<t-tag v-if="row.file_name" theme="success" variant="light" size="small" class="material-file-tag">附件</t-tag>
|
||||
</template>
|
||||
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
|
||||
<!-- 创建人(联查 users):记录课程由谁录入 -->
|
||||
<template #creator_name="{ row }">{{ row.creator_name || '-' }}</template>
|
||||
<template #publish_status="{ row }">
|
||||
<t-tag
|
||||
:theme="row.publish_status === 'published' ? 'success' : row.publish_status === 'offline' ? 'default' : 'warning'"
|
||||
@@ -452,6 +454,7 @@ import {
|
||||
exportCourseLibrary,
|
||||
fetchCourseCategories,
|
||||
generateLibraryCourseQuestions,
|
||||
getMyProfile,
|
||||
getTrainingKnowledgeBases,
|
||||
importCourseLibrary,
|
||||
importGeneratedQuestionBank,
|
||||
@@ -487,6 +490,8 @@ const members = ref<TrainingMember[]>([])
|
||||
const depts = ref<TrainingDept[]>([])
|
||||
// 课程分类选项 = 配置中心「课程分类」字典(fetchCourseCategories 缺失回退默认)
|
||||
const configCategories = ref<string[]>([])
|
||||
// 本人所在部门 id:新增课程「所属部门」默认当前登录用户所在部门(getMyProfile)
|
||||
const myDeptId = ref('')
|
||||
|
||||
// ---- 查询条件(编号/名称/分类/类型/形式;列表全量加载,本地过滤) ----
|
||||
const filters = ref({ keyword: '', category: '', type: '', mode: '' })
|
||||
@@ -530,6 +535,8 @@ const columns = [
|
||||
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
|
||||
{ colKey: 'publish_status', title: '发布状态', width: 90 },
|
||||
{ colKey: 'created_at', title: '创建时间', width: 140 },
|
||||
// 创建人(联查 users):记录课程录入人员
|
||||
{ colKey: 'creator_name', title: '创建人', width: 96 },
|
||||
{ colKey: 'op', title: '操作', width: 280, fixed: 'right' },
|
||||
]
|
||||
|
||||
@@ -539,16 +546,19 @@ const lecturerText = (row: TrainingLibraryCourse) =>
|
||||
const loadAll = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const [lib, m, d, cats] = await Promise.all([
|
||||
const [lib, m, d, cats, me] = await Promise.all([
|
||||
listCourseLibrary({ page_size: 500 }),
|
||||
listMembers({ page_size: 500 }).catch(() => null),
|
||||
listDepts().catch(() => null),
|
||||
fetchCourseCategories(),
|
||||
// 本人档案:新增课程「所属部门」默认当前登录用户所在部门
|
||||
getMyProfile().catch(() => null),
|
||||
])
|
||||
items.value = unwrap(lib)?.items || []
|
||||
members.value = (m && unwrap(m)?.items) || []
|
||||
depts.value = (d && unwrap(d)) || []
|
||||
configCategories.value = cats
|
||||
myDeptId.value = (me && unwrap(me)?.dept_id) || ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -670,7 +680,8 @@ const openForm = (row?: TrainingLibraryCourse) => {
|
||||
id: row?.id || '',
|
||||
code: row?.code || '',
|
||||
name: row?.name || '',
|
||||
owner_dept_id: row?.owner_dept_id || '',
|
||||
// 新增默认当前登录用户所在部门;编辑保持原部门
|
||||
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
|
||||
description: row?.description || '',
|
||||
suitable_members: row?.suitable_members || '',
|
||||
category: row?.category || '',
|
||||
@@ -830,6 +841,38 @@ const normMode = (raw: string): 'offline' | 'online' => (/线上/.test(raw) ? 'o
|
||||
// 课件收集列的占位文案(已有课件/暂无课件/无等)是状态标记,不落名称登记
|
||||
const isNoMaterial = (raw: string) => /^(已有课件|暂无课件|暂无|无课件|无)$/.test(raw)
|
||||
|
||||
// 表头键归一:去空白与全/半角括号、冒号等标点并转小写(兼容「课程说明(选填)」
|
||||
// 「时长:(学时)」这类自定义模板变体;配置中心上传的自定义模板表头可能带修饰)
|
||||
const normHeaderKey = (s: string) => String(s).trim().toLowerCase().replace(/[\s::,,、。.·()()[\]【】-]/g, '')
|
||||
|
||||
// 列名别名表(归一后口径):先精确命中,再按「表头包含别名」兜底,
|
||||
// 覆盖内置模板/旧口径/自定义模板的常见列名变体
|
||||
const IMPORT_HEADER_ALIASES: Record<string, string[]> = {
|
||||
name: ['课程名称', '名称'],
|
||||
dept: ['所属部门', '主办单位', '部门'],
|
||||
description: ['课程说明', '说明', '课程简介', '简介'],
|
||||
suitable: ['适合人员', '参加人员', '适合对象', '参训人员'],
|
||||
category: ['课程分类', '分类'],
|
||||
type: ['类型必修课或选修课', '类型'],
|
||||
mode: ['线上或线下', '线上线下', '形式'],
|
||||
lecturer: ['讲师姓名', '授课讲师', '培训讲师', '讲师'],
|
||||
hours: ['时长学时', '时长'],
|
||||
material: ['课件收集', '课件'],
|
||||
}
|
||||
|
||||
// 按别名组从归一化行中取值:别名精确 → 表头包含别名(首个命中),未命中返回 ''
|
||||
const pickImportColumn = (row: Record<string, string>, aliases: string[]) => {
|
||||
for (const a of aliases) {
|
||||
if (row[a]) return row[a]
|
||||
}
|
||||
const keys = Object.keys(row)
|
||||
for (const a of aliases) {
|
||||
const hit = keys.find((k) => k.includes(a))
|
||||
if (hit && row[hit]) return row[hit]
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const onImportExcel = async (e: Event) => {
|
||||
const input = e.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
@@ -837,13 +880,13 @@ const onImportExcel = async (e: Event) => {
|
||||
if (!file) return
|
||||
try {
|
||||
const wb = XLSX.read(await file.arrayBuffer())
|
||||
// 定位含「课程名称」表头的工作表;表头键做空白归一(兼容内含空格的列名)
|
||||
// 定位含「课程名称」表头的工作表;表头键做归一(空白/全半角标点,见 normHeaderKey)
|
||||
let dataRows: Record<string, string>[] | null = null
|
||||
for (const name of wb.SheetNames) {
|
||||
const sheetRows = XLSX.utils.sheet_to_json<string[]>(wb.Sheets[name], { header: 1, raw: false, defval: '' })
|
||||
const headerIdx = sheetRows.findIndex((r) => r.some((c) => String(c).trim() === '课程名称'))
|
||||
const headerIdx = sheetRows.findIndex((r) => r.some((c) => normHeaderKey(String(c)) === '课程名称'))
|
||||
if (headerIdx < 0) continue
|
||||
const header = (sheetRows[headerIdx] || []).map((c) => String(c).trim().replace(/\s+/g, ''))
|
||||
const header = (sheetRows[headerIdx] || []).map((c) => normHeaderKey(String(c)))
|
||||
dataRows = sheetRows.slice(headerIdx + 1).map((arr) => {
|
||||
const row: Record<string, string> = {}
|
||||
header.forEach((h, i) => {
|
||||
@@ -857,7 +900,8 @@ const onImportExcel = async (e: Event) => {
|
||||
MessagePlugin.error('未找到「课程名称」表头,请使用下载的课程管理导入模板填写')
|
||||
return
|
||||
}
|
||||
// 主办单位(所属部门)按部门名册匹配:名称精确 → 包含(与需求导入同口径),未匹配留空
|
||||
// 主办单位(所属部门)按部门名册匹配:名称精确 → 包含(与需求导入同口径),
|
||||
// 未匹配时仍把部门名传给后端(服务端按组织架构兜底解析为 id)
|
||||
const matchDept = (deptName: string) =>
|
||||
depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
|
||||
// 讲师按全部在职员工姓名精确匹配;未命中落外部讲师姓名(与需求导入同口径)
|
||||
@@ -867,13 +911,13 @@ const onImportExcel = async (e: Event) => {
|
||||
let externalLecturers = 0
|
||||
let deptHits = 0
|
||||
for (const row of dataRows) {
|
||||
const name = (row['课程名称'] || '').trim()
|
||||
const name = pickImportColumn(row, IMPORT_HEADER_ALIASES.name)
|
||||
if (!name) {
|
||||
skippedRows += 1
|
||||
continue
|
||||
}
|
||||
let ownerDeptId = ''
|
||||
const deptName = (row['所属部门'] || row['主办单位'] || '').trim()
|
||||
const deptName = pickImportColumn(row, IMPORT_HEADER_ALIASES.dept)
|
||||
if (deptName) {
|
||||
const hit = matchDept(deptName)
|
||||
if (hit) {
|
||||
@@ -883,7 +927,7 @@ const onImportExcel = async (e: Event) => {
|
||||
}
|
||||
let lecturerId = ''
|
||||
let lecturerExternal = ''
|
||||
const lecturerName = (row['讲师'] || '').trim()
|
||||
const lecturerName = pickImportColumn(row, IMPORT_HEADER_ALIASES.lecturer)
|
||||
if (lecturerName) {
|
||||
const hit = members.value.find((m) => (m.user_name || '') === lecturerName)
|
||||
if (hit?.user_id) {
|
||||
@@ -894,17 +938,18 @@ const onImportExcel = async (e: Event) => {
|
||||
externalLecturers += 1
|
||||
}
|
||||
}
|
||||
const hoursRaw = Number.parseFloat((row['时长(学时)'] || row['时长'] || '').replace(/[^\d.]/g, ''))
|
||||
const materialRaw = (row['课件收集'] || row['课件'] || '').trim()
|
||||
const hoursRaw = Number.parseFloat(pickImportColumn(row, IMPORT_HEADER_ALIASES.hours).replace(/[^\d.]/g, ''))
|
||||
const materialRaw = pickImportColumn(row, IMPORT_HEADER_ALIASES.material)
|
||||
// 类型/线上或线下:模板下拉列为全称表头(类型(必修课或选修课)/线上或线下),旧口径短表头同样兼容
|
||||
itemsPayload.push({
|
||||
name,
|
||||
owner_dept_id: ownerDeptId || undefined,
|
||||
description: (row['课程说明'] || row['说明'] || '').trim(),
|
||||
suitable_members: (row['适合人员'] || row['参加人员'] || '').trim(),
|
||||
category: (row['课程分类'] || row['分类'] || '').trim(),
|
||||
type: normType(row['类型(必修课或选修课)'] || row['类型'] || ''),
|
||||
mode: normMode(row['线上或线下'] || row['线上/线下'] || ''),
|
||||
owner_dept_name: deptName || undefined,
|
||||
description: pickImportColumn(row, IMPORT_HEADER_ALIASES.description),
|
||||
suitable_members: pickImportColumn(row, IMPORT_HEADER_ALIASES.suitable),
|
||||
category: pickImportColumn(row, IMPORT_HEADER_ALIASES.category),
|
||||
type: normType(pickImportColumn(row, IMPORT_HEADER_ALIASES.type)),
|
||||
mode: normMode(pickImportColumn(row, IMPORT_HEADER_ALIASES.mode)),
|
||||
lecturer_id: lecturerId || undefined,
|
||||
lecturer_external: lecturerExternal || undefined,
|
||||
hours: Number.isFinite(hoursRaw) && hoursRaw > 0 ? hoursRaw : 0,
|
||||
|
||||
@@ -76,6 +76,9 @@
|
||||
</t-tooltip>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<!-- 创建人(提报人姓名)/创建时间:记录需求由谁何时录入 -->
|
||||
<template #submitter_name="{ row }">{{ row.submitter_name || '-' }}</template>
|
||||
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
|
||||
<template #check_status="{ row }">
|
||||
<t-tag v-if="row.check_status === 'passed'" theme="success" variant="light" size="small">已确认</t-tag>
|
||||
<t-tag v-else-if="row.check_status === 'pending'" theme="warning" variant="light" size="small">待核验</t-tag>
|
||||
@@ -194,7 +197,7 @@
|
||||
:autosize="{ minRows: 6 }"
|
||||
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
|
||||
/>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/培訓費用/内/外培训(内部或外部,下拉选择)/计划培训月份(1~12,下拉选择)/讲师/备注;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/内/外培训(下拉选择内部或外部)/计划培训月份(1~12,下拉选择)/讲师/备注;费用列已移除;备注右侧为「调研维度与培训策划要求」说明列,无需填写;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
|
||||
</template>
|
||||
@@ -207,6 +210,7 @@
|
||||
<span class="collect-template-name">教育训练需求表模板(填写后经「批量导入」上传,或「在线提报需求」逐条填写)</span>
|
||||
<t-button variant="outline" size="small" @click="onDownloadDemandTemplate">下载模板</t-button>
|
||||
</div>
|
||||
<div class="form-hint">企微推送的消息尾部会自动附带「下载教育训练需求表模板」直链(20 天内有效)与「查看更多详情>>」入口,课长点击即可下载模板或进入企业培训系统。</div>
|
||||
<div class="collect-section-title">发送人员</div>
|
||||
<t-select
|
||||
v-model="collectForm.userIds"
|
||||
@@ -234,12 +238,16 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
import { DEMAND_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
|
||||
import { apiErrorMessage } from '@/utils/request'
|
||||
import {
|
||||
broadcastTrainingNotification,
|
||||
confirmDemand,
|
||||
DEFAULT_DEMAND_COLLECT_CONTENT,
|
||||
DEFAULT_DEMAND_COLLECT_TITLE,
|
||||
deleteDemand,
|
||||
fetchDemandCollectText,
|
||||
getMyProfile,
|
||||
importDemands,
|
||||
listCourseLibrary,
|
||||
@@ -385,6 +393,9 @@ const demandColumns = [
|
||||
{ colKey: 'train_type', title: '内/外培训', width: 90 },
|
||||
{ colKey: 'location', title: '地点', width: 100 },
|
||||
{ colKey: 'remark', title: '备注', minWidth: 140 },
|
||||
// 创建人(提报人)/创建时间:记录需求录入人员与时间
|
||||
{ colKey: 'submitter_name', title: '创建人', width: 96 },
|
||||
{ colKey: 'created_at', title: '创建时间', width: 140 },
|
||||
// 状态/操作固定在列表右侧,横向滚动时始终可见
|
||||
{ colKey: 'check_status', title: '状态', width: 84, fixed: 'right' },
|
||||
{ colKey: 'op', title: '操作', width: 160, fixed: 'right' },
|
||||
@@ -858,7 +869,10 @@ const collectVisible = ref(false)
|
||||
const collectSending = ref(false)
|
||||
const members = ref<TrainingMember[]>([])
|
||||
const membersLoading = ref(false)
|
||||
const collectForm = ref({ userIds: [] as string[], content: '' })
|
||||
const collectForm = ref({ userIds: [] as string[], title: '', content: '' })
|
||||
|
||||
// {year} 占位符替换为收集年度(下一年;与配置中心文案模板口径一致)
|
||||
const renderCollectTpl = (tpl: string) => tpl.split('{year}').join(String(nextYear))
|
||||
|
||||
// 推送人员下拉展示:姓名/工号 · 岗位 · 部门
|
||||
const memberLabel = (m: TrainingMember) =>
|
||||
@@ -874,10 +888,15 @@ const defaultCollectUserIds = () =>
|
||||
.map((m) => m.user_id)
|
||||
|
||||
const openCollect = async () => {
|
||||
collectForm.value.content =
|
||||
`请各部门于 ${nextYear} 年 1 月 31 日前,登录 AIDO → 企业培训 → 培训计划 → 年度需求收集,` +
|
||||
`提报 ${nextYear} 年度培训需求:可在线逐条提报,或下载「教育训练需求表模板」批量填写后导入。`
|
||||
// [2026-11 需求] 收集推送文案可配(配置中心「提醒推送文案」卡):先以内置
|
||||
// 默认渲染 {year} 打底(拉取失败也不空白),再异步回读配置覆盖预填文案
|
||||
collectForm.value.title = renderCollectTpl(DEFAULT_DEMAND_COLLECT_TITLE)
|
||||
collectForm.value.content = renderCollectTpl(DEFAULT_DEMAND_COLLECT_CONTENT)
|
||||
collectVisible.value = true
|
||||
fetchDemandCollectText().then((tpl) => {
|
||||
collectForm.value.title = renderCollectTpl(tpl.title)
|
||||
collectForm.value.content = renderCollectTpl(tpl.content)
|
||||
})
|
||||
// 名册只拉一次;每次打开按默认角色重置推送人员(支持在此基础上增删)
|
||||
if (!members.value.length) {
|
||||
membersLoading.value = true
|
||||
@@ -903,10 +922,12 @@ const onSendCollect = async () => {
|
||||
const res = await broadcastTrainingNotification({
|
||||
user_ids: collectForm.value.userIds,
|
||||
scene: 'demand_collect',
|
||||
title: `【培训需求收集】${nextYear}年度培训计划收集`,
|
||||
title: collectForm.value.title || renderCollectTpl(DEFAULT_DEMAND_COLLECT_TITLE),
|
||||
content: collectForm.value.content,
|
||||
ref_type: 'plan',
|
||||
ref_id: String(nextYear),
|
||||
// 前端 origin:后端据此在企微消息尾部拼模板签名下载链接与「查看更多详情」入口
|
||||
link_url: window.location.origin,
|
||||
})
|
||||
MessagePlugin.success(`已推送通知 ${unwrap(res)?.sent ?? 0} 人(站内 + 企业微信;未绑定企微的同事仅站内送达,可在配置中心查看推送记录)`)
|
||||
collectVisible.value = false
|
||||
|
||||
@@ -342,6 +342,8 @@ import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
COURSE_CATEGORY_DICT_RULE_KEY,
|
||||
DEFAULT_COURSE_CATEGORIES,
|
||||
DEFAULT_DEMAND_COLLECT_CONTENT,
|
||||
DEFAULT_DEMAND_COLLECT_TITLE,
|
||||
ROLE_DICT_RULE_KEY,
|
||||
deleteTrainingTemplate,
|
||||
fetchRoleDict,
|
||||
@@ -584,13 +586,25 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
? {}
|
||||
: { enabled: saved?.enabled !== false, hour: Number(saved?.hour ?? 9) },
|
||||
},
|
||||
{
|
||||
// [2026-11 需求] 企微消息内深链接的环境级基址覆盖:多入口(域名/IP、内外网)
|
||||
// 部署时固定链接指向权威域名,优先于推送人浏览器 origin;清空保存即回落 origin
|
||||
// (本地开发零配置可用)。demand_collect 推送的「下载模板/查看更多详情」共用。
|
||||
key: 'notify_link_base_url',
|
||||
group: 'notify',
|
||||
title: '推送链接基址',
|
||||
desc: '企微推送消息内「下载模板/查看更多详情」链接的对外地址;多入口或内外网部署时请填写课长实际访问的权威地址(如 https://aido.corp.com),留空则跟随推送人当前访问地址',
|
||||
fields: [{ key: 'base_url', label: '对外基址', type: 'text', placeholder: 'https://aido.corp.com' }],
|
||||
serialize: (v) => String(v.base_url || '').trim(),
|
||||
parse: (saved) => ({ base_url: typeof saved === 'string' ? saved : '' }),
|
||||
},
|
||||
{
|
||||
// [2026-11 需求] 提醒推送文案可编辑:各提醒场景的标题/内容模板,保存后新推送即刻生效;
|
||||
// {占位符} 渲染时替换为实际值,清空保存即恢复内置默认文案(后端空值回落默认)。
|
||||
key: 'notify_text_templates',
|
||||
group: 'notify',
|
||||
title: '提醒推送文案',
|
||||
desc: '各提醒推送的标题与内容模板,支持 {占位符} 替换实际值;清空并保存即恢复内置默认文案,对保存后的新推送生效',
|
||||
desc: '各提醒与年培训计划收集推送的标题与内容模板,支持 {占位符} 替换实际值;清空并保存即恢复内置默认文案,对保存后的新推送生效',
|
||||
fields: [
|
||||
{
|
||||
key: 'student_notice_title',
|
||||
@@ -628,6 +642,21 @@ const RULE_SCHEMAS: RuleSchemaDesc[] = [
|
||||
type: 'text',
|
||||
vars: '{year} / {month} / {week} / {week_start} / {week_end} 本周起止(MM-DD) / {count} 未结束场次',
|
||||
},
|
||||
{
|
||||
// [2026-11 需求] 年培训计划收集推送(培训计划页「收集下年度计划」弹窗):
|
||||
// 弹窗预填与后端广播空字段回落共用本模板,{year} 渲染为收集年度(下一年)。
|
||||
key: 'demand_collect_title',
|
||||
label: '年培训计划收集推送 · 标题',
|
||||
type: 'text',
|
||||
placeholder: DEFAULT_DEMAND_COLLECT_TITLE,
|
||||
vars: '{year} 收集年度(推送时按下一年度替换)',
|
||||
},
|
||||
{
|
||||
key: 'demand_collect_content',
|
||||
label: '年培训计划收集推送 · 内容',
|
||||
type: 'text',
|
||||
vars: '{year} 收集年度(推送时按下一年度替换)',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -655,6 +684,7 @@ const DEFAULT_RULE_VALUES: Record<string, Record<string, any>> = {
|
||||
notify_remind_days: { t3: true, t1: true },
|
||||
notify_push_enabled: { enabled: true },
|
||||
notify_weekly_lecturer: { enabled: true, hour: 9 },
|
||||
notify_link_base_url: { base_url: '' },
|
||||
// [2026-11 需求] 提醒推送文案默认模板(与后端 defaultNotifyTextTemplates 逐字一致)
|
||||
notify_text_templates: {
|
||||
student_notice_title: '培训开课通知',
|
||||
@@ -667,6 +697,9 @@ const DEFAULT_RULE_VALUES: Record<string, Record<string, any>> = {
|
||||
weekly_title: '{year}年{month}月教育训练(第{week}周提醒)',
|
||||
weekly_content:
|
||||
'{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。',
|
||||
// 年培训计划收集推送默认文案(与后端 defaultDemandCollect* 同源引用)
|
||||
demand_collect_title: DEFAULT_DEMAND_COLLECT_TITLE,
|
||||
demand_collect_content: DEFAULT_DEMAND_COLLECT_CONTENT,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
* 未上传时由后端回退内置默认(docs/moban 随二进制分发)。
|
||||
* - demand_collection 教育训练需求表模板.xlsx(2026-11 起的系统内置默认,
|
||||
* 含「计划培训月份」列):培训计划「年度需求收集 → 批量导入」使用;
|
||||
* 列:编号/部门/课程名称/参加人员/地点/培訓費用/內外培訓/计划培训月份/讲师/备注;
|
||||
* 列:编号/部门/课程名称/适合人员/地点/內外培訓/计划培训月份/讲师/备注
|
||||
* (旧口径「培訓費用」列下载时由后端动态删除,右侧列左移;
|
||||
* 备注右侧动态追加「调研维度/培训策划要求」说明列);
|
||||
* 后端下载时动态注入:标题年份=下一年度、课程名称下拉(课程管理 C)、
|
||||
* 计划培训月份下拉(1~12 H)、部门/讲师下拉(部门 B/讲师 I)。
|
||||
* 计划培训月份下拉(1~12 G)、部门/讲师下拉(部门 B/讲师 H)。
|
||||
* - question_bank 部门培训课程试题(题库导入版)模板.xlsx:
|
||||
* 「题库与考试 → Excel 批量导入」与「培训课程 → 创建课程 → 关联题库」指引使用;
|
||||
* 工作表:单选题/多选题/判断题,列:题目/课程名称/难度/正确答案/答案A..答案L。
|
||||
|
||||
@@ -39,10 +39,12 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
}
|
||||
var items []*types.TrainingCourseLibrary
|
||||
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id);
|
||||
// creator_name 联查创建人姓名(display_name 优先,回退 username 工号)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
|
||||
Order("tr_course_library.updated_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&items).Error
|
||||
@@ -53,9 +55,10 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||
var item types.TrainingCourseLibrary
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
|
||||
Where("tr_course_library.tenant_id = ? AND tr_course_library.id = ?", tenantID, id).First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -58,11 +58,13 @@ func (r *trainingRepository) ListDemands(ctx context.Context, tenantID uint64, q
|
||||
}
|
||||
var items []*types.TrainingDemand
|
||||
// lecturer_name 同口径取真实姓名(display_name 优先,回退 username 工号;
|
||||
// lecturer_id 为空或用户已删时回退外部讲师姓名 lecturer_external)。
|
||||
// lecturer_id 为空或用户已删时回退外部讲师姓名 lecturer_external);
|
||||
// submitter_name 联查提报人姓名(年培训计划「创建人」列)。
|
||||
err := filter().
|
||||
Select("tr_demands.*, COALESCE(dp.name, '') AS dept_name, COALESCE(NULLIF(lu.display_name, ''), lu.username, tr_demands.lecturer_external, '') AS lecturer_name").
|
||||
Select("tr_demands.*, COALESCE(dp.name, '') AS dept_name, COALESCE(NULLIF(lu.display_name, ''), lu.username, tr_demands.lecturer_external, '') AS lecturer_name, COALESCE(NULLIF(su.display_name, ''), su.username, '') AS submitter_name").
|
||||
Joins("LEFT JOIN org_depts dp ON dp.id = tr_demands.dept_id AND dp.tenant_id = tr_demands.tenant_id AND dp.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_demands.lecturer_id").
|
||||
Joins("LEFT JOIN users su ON su.id = tr_demands.submitter_id").
|
||||
Order("tr_demands.created_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&items).Error
|
||||
|
||||
@@ -687,15 +687,15 @@ func (s *trainingService) RollMonthPlans(ctx context.Context, tenantID uint64, f
|
||||
}
|
||||
}
|
||||
plan := &types.TrainingMonthPlan{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
Year: nextYear,
|
||||
Month: nextMonth,
|
||||
Title: courseName,
|
||||
Status: types.TrainingMonthPlanDraft,
|
||||
RollFromID: session.ID,
|
||||
RollTimes: rollTimes,
|
||||
Escalated: rollTimes >= 2, // 连续两月未完成升级并抄送人事
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
Year: nextYear,
|
||||
Month: nextMonth,
|
||||
Title: courseName,
|
||||
Status: types.TrainingMonthPlanDraft,
|
||||
RollFromID: session.ID,
|
||||
RollTimes: rollTimes,
|
||||
Escalated: rollTimes >= 2, // 连续两月未完成升级并抄送人事
|
||||
SubmitterID: operatorID,
|
||||
}
|
||||
if err := s.repo.CreateMonthPlan(ctx, plan); err != nil {
|
||||
|
||||
@@ -2,11 +2,14 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
@@ -46,11 +49,11 @@ func TestBroadcastNotificationRepeatsDeliver(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
users := []string{"u-1", "u-2", "u-3", "u-4"}
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(users), sent)
|
||||
|
||||
sent2, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027")
|
||||
sent2, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(users), sent2)
|
||||
|
||||
@@ -70,7 +73,7 @@ func TestBroadcastNotificationPushToggle(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
@@ -83,7 +86,7 @@ func TestBroadcastNotificationPushToggle(t *testing.T) {
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID, RuleKey: "notify_push_enabled", RuleValue: types.JSON([]byte("false")),
|
||||
}).Error)
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows = countBroadcastRows(t, db, tenantID)
|
||||
@@ -98,14 +101,153 @@ func TestBroadcastNotificationValidation(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.BroadcastNotification(ctx, tenantID, nil, "demand_collect", "t", "c", "plan", "2027")
|
||||
_, err := svc.BroadcastNotification(ctx, tenantID, nil, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "请选择推送人员")
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"", "u-1", ""}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"", "u-1", ""}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, "u-1", rows[0].TargetUserID, "空串 user_id 应被跳过,只落有效收件人")
|
||||
}
|
||||
|
||||
// [2026-11 需求] demand_collect 广播带 link_url:归一化尾部斜杠落库,并为
|
||||
// 教育训练需求表模板签发可校验的匿名下载 token;其他场景/非法地址一律空,
|
||||
// 链接是增强不是前提(核验/确认等站内广播不受影响)。
|
||||
func TestBroadcastNotificationDeepLink(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1", "u-2"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "https://aido.example.com/")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
require.Len(t, rows, 2)
|
||||
for _, row := range rows {
|
||||
require.Equal(t, "https://aido.example.com", row.LinkURL, "尾部斜杠应归一化")
|
||||
require.NotEmpty(t, row.LinkToken)
|
||||
payload, err := utils.VerifyTrainingTemplateToken(row.LinkToken)
|
||||
require.NoError(t, err, "落库 token 必须可回验")
|
||||
require.Equal(t, tenantID, payload.TenantID)
|
||||
require.Equal(t, types.TrainingTemplateDemandCollection, payload.TemplateKey)
|
||||
}
|
||||
|
||||
// 同一批广播共享同一 token(一次签名,整批复用)
|
||||
require.Equal(t, rows[0].LinkToken, rows[1].LinkToken)
|
||||
|
||||
// 非 demand_collect 场景:带 link_url 也不落链接
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_verify", "t", "c", "plan", "2027", "https://aido.example.com")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
var verifyRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&verifyRow).Error)
|
||||
require.Empty(t, verifyRow.LinkURL)
|
||||
require.Empty(t, verifyRow.LinkToken)
|
||||
|
||||
// 非法地址(非 http(s) 绝对地址)与空地址:不落链接
|
||||
for _, bad := range []string{"", "javascript:alert(1)", "/platform/training/plan"} {
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-4"},
|
||||
"demand_collect", "t", "c", "plan", "2027", bad)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
var plainRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-4").
|
||||
Order("created_at DESC").First(&plainRow).Error)
|
||||
require.Empty(t, plainRow.LinkURL)
|
||||
require.Empty(t, plainRow.LinkToken)
|
||||
}
|
||||
|
||||
// [2026-11 需求] 环境级基址覆盖:配置中心 notify_link_base_url 优先于推送人
|
||||
// 浏览器 origin —— 多入口/内外网部署时链接固定指向权威域名,本地开发不配置
|
||||
// 则回落 origin;覆盖值非法时回落 origin,再非法则不落链接。
|
||||
func TestBroadcastNotificationLinkBaseOverride(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
RuleKey: "notify_link_base_url", RuleValue: types.JSON([]byte(`"https://aido.corp.com"`)),
|
||||
}).Error)
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "http://localhost:5173")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
var row types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-1").First(&row).Error)
|
||||
require.Equal(t, "https://aido.corp.com", row.LinkURL, "环境覆盖应优先于推送 origin")
|
||||
require.NotEmpty(t, row.LinkToken)
|
||||
|
||||
// 覆盖值非法(非 http(s))→ 回落推送 origin
|
||||
require.NoError(t, db.Model(&types.TrainingRuleConfig{}).
|
||||
Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_link_base_url").
|
||||
Update("rule_value", types.JSON([]byte(`"not-a-url"`))).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "http://localhost:5173")
|
||||
require.NoError(t, err)
|
||||
var fallbackRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-2").First(&fallbackRow).Error)
|
||||
require.Equal(t, "http://localhost:5173", fallbackRow.LinkURL)
|
||||
|
||||
// 覆盖与 origin 均空/非法 → 不落链接
|
||||
require.NoError(t, db.Model(&types.TrainingRuleConfig{}).
|
||||
Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_link_base_url").
|
||||
Update("rule_value", types.JSON([]byte(`""`))).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
var emptyRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&emptyRow).Error)
|
||||
require.Empty(t, emptyRow.LinkURL)
|
||||
}
|
||||
|
||||
// [2026-11 需求] 年培训计划收集推送文案可配(notify_text_templates
|
||||
// demand_collect_*):广播空标题/内容按模板回落渲染,{year} 以 ref_id
|
||||
// 收集年度替换;调用方显式传入的文案不被覆盖;字段清空回落内置默认。
|
||||
func TestBroadcastNotificationDemandCollectTextTemplates(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 配置中心自定义收集文案
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
RuleKey: "notify_text_templates",
|
||||
RuleValue: types.JSON([]byte(`{"demand_collect_title":"【年度计划】{year}年需求提报",
|
||||
"demand_collect_content":"请于 {year} 年提报年度培训需求。","weekly_title":""}`)),
|
||||
}).Error)
|
||||
|
||||
// 空标题/内容 → 模板渲染;显式传入 → 原样保留
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"},
|
||||
"demand_collect", "", "", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"},
|
||||
"demand_collect", "手写标题", "手写内容", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
|
||||
var tplRow, explicitRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-1").First(&tplRow).Error)
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-2").First(&explicitRow).Error)
|
||||
require.Equal(t, "【年度计划】2027年需求提报", tplRow.Title)
|
||||
require.Equal(t, "请于 2027 年提报年度培训需求。", tplRow.Content)
|
||||
require.Equal(t, "手写标题", explicitRow.Title)
|
||||
require.Equal(t, "手写内容", explicitRow.Content)
|
||||
|
||||
// 字段清空(回落内置默认)且 ref_id 不带年份前缀 → {year} 渲染为下一年
|
||||
require.NoError(t, db.Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_text_templates").
|
||||
Delete(&types.TrainingRuleConfig{}).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_collect", "", "", "plan", "", "")
|
||||
require.NoError(t, err)
|
||||
var fallbackRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&fallbackRow).Error)
|
||||
nextYear := beijingNow(time.Now()).Year() + 1
|
||||
require.Equal(t, fmt.Sprintf("【培训需求收集】%d年度培训计划收集", nextYear), fallbackRow.Title)
|
||||
require.Contains(t, fallbackRow.Content,
|
||||
fmt.Sprintf("请各部门于 %d 年 1 月 31 日前提报 %d 年度培训需求", nextYear, nextYear))
|
||||
}
|
||||
@@ -12,12 +12,15 @@ import (
|
||||
"path"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"academy/internal/utils"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
@@ -1426,16 +1429,35 @@ func (s *trainingService) Notify(ctx context.Context, tenantID uint64, targetUse
|
||||
// 运营场景),站内 + 企微外箱(调度器 dispatchPending 消费)。手动广播是离散
|
||||
// 的发送动作:ref_id 追加发送时间戳,避免与唯一索引 (tenant,target,scene,ref)
|
||||
// 冲突把已收过通知的人静默去重;返回成功入箱条数。
|
||||
func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID string) (int, error) {
|
||||
// linkURL 为前端 origin(可空):demand_collect 场景据此生成教育训练需求表
|
||||
// 模板的匿名下载签名 token(20 天有效)随行落库,调度器投递企微时拼尾部
|
||||
// 「下载模板/查看详情」链接;站内 content 保持纯文本不受影响。
|
||||
// demand_collect 场景空标题/内容按配置中心文案模板回落渲染(见 training_notify.go)。
|
||||
func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID, linkURL string) (int, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return 0, errors.NewBadRequestError("请选择推送人员")
|
||||
}
|
||||
if scene == "" {
|
||||
scene = "demand_collect"
|
||||
scene = types.SceneDemandCollect
|
||||
}
|
||||
// [2026-11 需求] 年培训计划收集推送文案:配置中心「提醒推送文案」卡
|
||||
// (notify_text_templates demand_collect_*)可编辑;调用方未带标题/内容时
|
||||
// 按模板回落渲染,{year} 取 ref_id 收集年度(缺省北京时间下一年)。
|
||||
if scene == types.SceneDemandCollect {
|
||||
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
|
||||
year := strconv.Itoa(demandCollectYear(refID, time.Now()))
|
||||
vars := map[string]string{"year": year}
|
||||
if strings.TrimSpace(title) == "" {
|
||||
title = renderNotifyTemplate(tpl.DemandCollectTitle, vars)
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
content = renderNotifyTemplate(tpl.DemandCollectContent, vars)
|
||||
}
|
||||
}
|
||||
if refID != "" {
|
||||
refID = fmt.Sprintf("%s-%d", refID, time.Now().UnixNano())
|
||||
}
|
||||
linkURL, linkToken := s.broadcastDeepLink(ctx, tenantID, scene, linkURL)
|
||||
push := s.loadPushEnabled(ctx, tenantID)
|
||||
now := time.Now()
|
||||
status := ""
|
||||
@@ -1451,6 +1473,7 @@ func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID ui
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
TargetUserID: uid, Channel: "inapp", Scene: scene,
|
||||
Title: title, Content: content, RefType: refType, RefID: refID,
|
||||
LinkURL: linkURL, LinkToken: linkToken,
|
||||
SentAt: now, PushStatus: status,
|
||||
})
|
||||
}
|
||||
@@ -1463,6 +1486,60 @@ func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID ui
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// broadcastDeepLink 解析广播外链基址并为 demand_collect 场景签发模板匿名
|
||||
// 下载 token。基址取值优先级:配置中心 notify_link_base_url(环境级覆盖,
|
||||
// 多入口/内外网部署固定指向权威域名)> 前端推送 origin(window.location.origin,
|
||||
// 本地开发零配置可用)。仅接受 http(s) 绝对地址;非法或非收集场景一律退回
|
||||
// 空串,不阻断通知本身(链接是增强,不是前提)。
|
||||
func (s *trainingService) broadcastDeepLink(ctx context.Context, tenantID uint64, scene, linkURL string) (string, string) {
|
||||
if scene != types.SceneDemandCollect {
|
||||
return "", ""
|
||||
}
|
||||
linkURL = normalizeLinkBase(s.loadLinkBaseOverride(ctx, tenantID), linkURL)
|
||||
if linkURL == "" {
|
||||
return "", ""
|
||||
}
|
||||
token, err := utils.SignTrainingTemplateToken(&utils.TrainingTemplateTokenPayload{
|
||||
TenantID: tenantID,
|
||||
TemplateKey: types.TrainingTemplateDemandCollection,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingBroadcast] sign template download token: %v", err)
|
||||
return "", ""
|
||||
}
|
||||
return linkURL, token
|
||||
}
|
||||
|
||||
// loadLinkBaseOverride 读配置中心 notify_link_base_url(bare string;空 = 未配置)。
|
||||
func (s *trainingService) loadLinkBaseOverride(ctx context.Context, tenantID uint64) string {
|
||||
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if rule.RuleKey == ruleKeyNotifyLinkBaseURL {
|
||||
var v string
|
||||
if json.Unmarshal(rule.RuleValue, &v) == nil {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// normalizeLinkBase 从候选(优先配置覆盖,其次调用方 origin)选出一个合法的
|
||||
// http(s) 基址:去空白与尾部斜杠;候选均非法时返回空串。
|
||||
func normalizeLinkBase(override, origin string) string {
|
||||
for _, candidate := range []string{override, origin} {
|
||||
candidate = strings.TrimRight(strings.TrimSpace(candidate), "/")
|
||||
if strings.HasPrefix(candidate, "http://") || strings.HasPrefix(candidate, "https://") {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 小工具
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -67,6 +67,33 @@ func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID u
|
||||
return s.repo.ListCourseLibrary(ctx, tenantID, q)
|
||||
}
|
||||
|
||||
// resolveCourseLibraryDept 所属部门兜底解析:新增/导入行仅传部门名(owner_dept_name,
|
||||
// 前端部门名册未加载或模板列口径不一致时)按组织架构匹配为 id:名称精确 →
|
||||
// 行值包含部门名(与需求导入同口径)。解析失败保持原值(留空即列表「-」),不阻断导入。
|
||||
func (s *trainingService) resolveCourseLibraryDept(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary) {
|
||||
name := strings.TrimSpace(item.OwnerDeptName)
|
||||
if item.OwnerDeptID != "" || name == "" {
|
||||
return
|
||||
}
|
||||
depts, err := s.org.ListDepts(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Skip course library dept name resolve, tenant=%d dept=%s error: %v", tenantID, name, err)
|
||||
return
|
||||
}
|
||||
for _, d := range depts {
|
||||
if d.Name == name {
|
||||
item.OwnerDeptID = d.ID
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, d := range depts {
|
||||
if d.Name != "" && strings.Contains(name, d.Name) {
|
||||
item.OwnerDeptID = d.ID
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。
|
||||
func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
@@ -76,6 +103,8 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
|
||||
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
||||
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||
@@ -148,6 +177,8 @@ func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
continue // 缺课程名称的行跳过(前端同步提示跳过行数)
|
||||
}
|
||||
// 仅传部门名的行按组织架构解析为 id(前端匹配失败/未传 id 的兜底)。
|
||||
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
@@ -190,7 +221,7 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
|
||||
// 列口径对齐《教育训练需求表》:所属部门=主办单位,适合人员=参加人员,
|
||||
// 课件=课件收集;导入解析端(LibraryPanel onImportExcel)两套列名均兼容。
|
||||
headers := []string{"课程编号", "所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
|
||||
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建时间"}
|
||||
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建人", "创建时间"}
|
||||
for i, h := range headers {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
_ = f.SetCellValue(sheet, cell, h)
|
||||
@@ -208,7 +239,7 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
|
||||
}
|
||||
values := []string{item.Code, item.OwnerDeptName, item.Name, item.Description, item.SuitableMembers, item.Category,
|
||||
courseLibraryTypeLabel(item.Type), courseLibraryModeLabel(item.Mode),
|
||||
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatedAt.Format("2006-01-02 15:04")}
|
||||
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatorName, item.CreatedAt.Format("2006-01-02 15:04")}
|
||||
for i, v := range values {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, r+2)
|
||||
_ = f.SetCellValue(sheet, cell, v)
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// 周一讲师汇总提醒的规则键(ruleKeyNotifyWeeklyLecturer* 定义在
|
||||
@@ -121,6 +122,9 @@ type notifyTextTemplates struct {
|
||||
// 周一讲师未完成汇总提醒:标题与内容
|
||||
WeeklyTitle string `json:"weekly_title"`
|
||||
WeeklyContent string `json:"weekly_content"`
|
||||
// 年培训计划收集推送(scene=demand_collect):广播空标题/内容回落渲染
|
||||
DemandCollectTitle string `json:"demand_collect_title"`
|
||||
DemandCollectContent string `json:"demand_collect_content"`
|
||||
}
|
||||
|
||||
// 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。
|
||||
@@ -133,6 +137,9 @@ const (
|
||||
defaultLecturerMaintainFooter = "该课程尚未上传课件/学习材料,请尽快登录培训平台补齐,以免影响学员课前学习。"
|
||||
defaultWeeklyTitle = "{year}年{month}月教育训练(第{week}周提醒)"
|
||||
defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
|
||||
// 年培训计划收集推送默认文案(与前端收集弹窗历史硬编码逐字一致;{year} 渲染收集年度)
|
||||
defaultDemandCollectTitle = "【培训需求收集】{year}年度培训计划收集"
|
||||
defaultDemandCollectContent = "请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。"
|
||||
)
|
||||
|
||||
func defaultNotifyTextTemplates() notifyTextTemplates {
|
||||
@@ -145,6 +152,8 @@ func defaultNotifyTextTemplates() notifyTextTemplates {
|
||||
LecturerMaintainFooter: defaultLecturerMaintainFooter,
|
||||
WeeklyTitle: defaultWeeklyTitle,
|
||||
WeeklyContent: defaultWeeklyContent,
|
||||
DemandCollectTitle: defaultDemandCollectTitle,
|
||||
DemandCollectContent: defaultDemandCollectContent,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +178,8 @@ func parseNotifyTextTemplates(raw []byte) notifyTextTemplates {
|
||||
fill(&t.LecturerMaintainFooter, saved.LecturerMaintainFooter)
|
||||
fill(&t.WeeklyTitle, saved.WeeklyTitle)
|
||||
fill(&t.WeeklyContent, saved.WeeklyContent)
|
||||
fill(&t.DemandCollectTitle, saved.DemandCollectTitle)
|
||||
fill(&t.DemandCollectContent, saved.DemandCollectContent)
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -562,6 +573,53 @@ func (s *trainingService) RunWeeklyLecturerReminders(ctx context.Context, tenant
|
||||
return s.enqueueWeeklyLecturerReminders(ctx, tenantID, time.Now(), s.loadPushEnabled(ctx, tenantID))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// demand_collect 年培训计划收集推送(2026-11 需求:文案可配 + 模板下载/详情入口)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// demandCollectYear 从广播 ref_id 前缀解析收集年度("2027-<纳秒>" → 2027,
|
||||
// 前端收集弹窗恒传下一年度);无合法年份前缀时回退北京时间下一年。
|
||||
func demandCollectYear(refID string, now time.Time) int {
|
||||
if idx := strings.IndexByte(refID, '-'); idx > 0 {
|
||||
refID = refID[:idx]
|
||||
}
|
||||
if year, err := strconv.Atoi(refID); err == nil && year >= 2000 && year <= 2999 {
|
||||
return year
|
||||
}
|
||||
return beijingNow(now).Year() + 1
|
||||
}
|
||||
|
||||
// demandCollectPlanPath 年培训计划页(前端铃铛 ref_type=plan 同款跳转目标)。
|
||||
const demandCollectPlanPath = "/platform/training/plan"
|
||||
|
||||
// wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。
|
||||
// demand_collect 且行内带 link_url 时追加两行 markdown 链接:
|
||||
//
|
||||
// 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略)
|
||||
// 查看更多详情>>(进入企业培训系统年培训计划页)
|
||||
//
|
||||
// 其余场景原样返回(提醒类场景的 markdown 由生成侧 remindContent 拼好)。
|
||||
func wecomDispatchContent(row *claimedNotification) string {
|
||||
if row.Scene != types.SceneDemandCollect || row.LinkURL == "" {
|
||||
return row.Content
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(strings.TrimRight(row.Content, "\n"))
|
||||
if row.LinkToken != "" {
|
||||
b.WriteString("\n\n[下载教育训练需求表模板](")
|
||||
b.WriteString(row.LinkURL)
|
||||
b.WriteString(utils.TrainingTemplateSignedFilePath)
|
||||
b.WriteString("?token=")
|
||||
b.WriteString(row.LinkToken)
|
||||
b.WriteString(")")
|
||||
}
|
||||
b.WriteString("\n[查看更多详情>>](")
|
||||
b.WriteString(row.LinkURL)
|
||||
b.WriteString(demandCollectPlanPath)
|
||||
b.WriteString(")")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 推送记录(管理台逐人明细)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -4,6 +4,7 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -17,12 +18,23 @@ func TestParseNotifyTextTemplatesFallsBackToDefaults(t *testing.T) {
|
||||
raw, err := json.Marshal(map[string]any{
|
||||
"student_notice_title": "自定义开课标题",
|
||||
"student_notice_content": "",
|
||||
"demand_collect_content": "自定义收集内容 {year}",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
got := parseNotifyTextTemplates(raw)
|
||||
require.Equal(t, "自定义开课标题", got.StudentNoticeTitle)
|
||||
require.Equal(t, defaultStudentNoticeContent, got.StudentNoticeContent)
|
||||
require.Equal(t, defaultWeeklyTitle, got.WeeklyTitle)
|
||||
require.Equal(t, defaultDemandCollectTitle, got.DemandCollectTitle)
|
||||
require.Equal(t, "自定义收集内容 {year}", got.DemandCollectContent)
|
||||
}
|
||||
|
||||
func TestDemandCollectYear(t *testing.T) {
|
||||
// ref_id 前缀为收集年度(带时间戳后缀同样可解析),非法/缺失回退下一年
|
||||
require.Equal(t, 2027, demandCollectYear("2027-1770000000000000000", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("2027", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("not-a-year", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
}
|
||||
|
||||
func TestRenderNotifyTemplate(t *testing.T) {
|
||||
|
||||
@@ -65,6 +65,10 @@ const (
|
||||
// ruleKeyNotifyTextTemplates [2026-11 需求] 提醒推送文案模板(配置中心可编辑,
|
||||
// 空字段回落 training_notify.go 的内置默认文案)。
|
||||
ruleKeyNotifyTextTemplates = "notify_text_templates"
|
||||
// ruleKeyNotifyLinkBaseURL [2026-11 需求] 企微消息内深链接的对外基址覆盖
|
||||
// (bare string,如 https://aido.example.com):多入口/内外网部署时固定链接
|
||||
// 指向权威域名,优先于推送人浏览器 origin;空 = 用推送人 origin。
|
||||
ruleKeyNotifyLinkBaseURL = "notify_link_base_url"
|
||||
)
|
||||
|
||||
// sendingReclaimAfter bounds how long a claimed row may stay 'sending'
|
||||
@@ -588,6 +592,8 @@ type claimedNotification struct {
|
||||
Scene string
|
||||
Title string
|
||||
Content string
|
||||
LinkURL string
|
||||
LinkToken string
|
||||
PushAttempts int
|
||||
}
|
||||
|
||||
@@ -604,7 +610,7 @@ func (s *TrainingScheduler) dispatchPending(ctx context.Context) error {
|
||||
FOR UPDATE SKIP LOCKED
|
||||
) AS c
|
||||
WHERE t.id = c.id
|
||||
RETURNING t.id, t.tenant_id, t.target_user_id, t.scene, t.title, t.content, t.push_attempts`,
|
||||
RETURNING t.id, t.tenant_id, t.target_user_id, t.scene, t.title, t.content, t.link_url, t.link_token, t.push_attempts`,
|
||||
pushStatusSending, pushStatusPending, s.cfg.DispatchBatch).
|
||||
Scan(&claimed).Error
|
||||
if err != nil {
|
||||
@@ -650,7 +656,7 @@ func (s *TrainingScheduler) dispatchTenant(ctx context.Context, tenantID uint64,
|
||||
case mapping[row.TargetUserID] == "":
|
||||
s.finishPush(ctx, row, pushStatusSkipped, nil, "缺少企微 userid 绑定")
|
||||
default:
|
||||
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, row.Content)
|
||||
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, wecomDispatchContent(row))
|
||||
if err == nil {
|
||||
s.finishPush(ctx, row, pushStatusSent, ptrTime(s.now()), "")
|
||||
continue
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
@@ -18,9 +19,9 @@ import (
|
||||
// fakeWecomBackend serves a fake sender plus a userid mapping to the
|
||||
// scheduler under test.
|
||||
type fakeWecomBackend struct {
|
||||
sender *fakePushSender
|
||||
sender *fakePushSender
|
||||
clientErr error
|
||||
mapping map[string]string
|
||||
mapping map[string]string
|
||||
lookupErr error
|
||||
}
|
||||
|
||||
@@ -40,15 +41,17 @@ func (f *fakeWecomBackend) TenantWecomUserIDs(context.Context, *gorm.DB, uint64,
|
||||
|
||||
// fakePushSender records SendMarkdown calls for dispatcher assertions.
|
||||
type fakePushSender struct {
|
||||
sent [][]string
|
||||
err error
|
||||
sent [][]string
|
||||
contents []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, _ string) error {
|
||||
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, content string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.sent = append(f.sent, userIDs)
|
||||
f.contents = append(f.contents, content)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -332,3 +335,54 @@ func TestRemindContent(t *testing.T) {
|
||||
require.Contains(t, maintain, "课程维护提醒")
|
||||
require.True(t, strings.Contains(maintain, "课件"), "maintain copy mentions materials")
|
||||
}
|
||||
|
||||
// [2026-11 需求] demand_collect 企微投递正文:行内带 link_url/link_token 时
|
||||
// 尾部拼「下载模板 + 查看详情」两行 markdown 链接;其他场景原样透传。
|
||||
func TestWecomDispatchContentDemandCollectFooter(t *testing.T) {
|
||||
token, err := utils.SignTrainingTemplateToken(&utils.TrainingTemplateTokenPayload{
|
||||
TenantID: 42, TemplateKey: types.TrainingTemplateDemandCollection,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("footer appended with download and details links", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneDemandCollect,
|
||||
Content: "请于 2027-01-31 前提报需求。", LinkURL: "https://aido.example.com", LinkToken: token}
|
||||
got := wecomDispatchContent(row)
|
||||
require.True(t, strings.HasPrefix(got, "请于 2027-01-31 前提报需求。"))
|
||||
require.Contains(t, got,
|
||||
"[下载教育训练需求表模板](https://aido.example.com"+utils.TrainingTemplateSignedFilePath+"?token="+token+")")
|
||||
require.Contains(t, got, "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
})
|
||||
|
||||
t.Run("missing token keeps details link only", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneDemandCollect,
|
||||
Content: "c", LinkURL: "https://aido.example.com"}
|
||||
got := wecomDispatchContent(row)
|
||||
require.NotContains(t, got, "signed-file")
|
||||
require.Contains(t, got, "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
})
|
||||
|
||||
t.Run("other scenes pass through untouched", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneSessionNoticeStudent,
|
||||
Content: "markdown body", LinkURL: "https://aido.example.com", LinkToken: token}
|
||||
require.Equal(t, "markdown body", wecomDispatchContent(row))
|
||||
})
|
||||
|
||||
t.Run("dispatch end-to-end sends composed markdown", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-1", Scene: types.SceneDemandCollect, Content: "c",
|
||||
LinkURL: "https://aido.example.com", LinkToken: token, PushStatus: pushStatusSending}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID,
|
||||
[]*claimedNotification{{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1",
|
||||
Scene: types.SceneDemandCollect, Content: "c",
|
||||
LinkURL: "https://aido.example.com", LinkToken: token}})
|
||||
|
||||
require.Len(t, f.backend.sender.contents, 1)
|
||||
require.Contains(t, f.backend.sender.contents[0], "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
require.Contains(t, f.backend.sender.contents[0], "signed-file?token=")
|
||||
})
|
||||
}
|
||||
@@ -123,16 +123,84 @@ const (
|
||||
// demandTitleYearRe 标题行年份(如「2026 年 度 教 育 训 练 需 求 表」)。
|
||||
var demandTitleYearRe = regexp.MustCompile(`20\d{2}`)
|
||||
|
||||
// demandTemplateNoteText 说明列文案(2026-11 模板调整):备注右侧合并单元格,
|
||||
// 调研维度(战略/组织/员工三层)+ 各部门培训策划硬性要求。
|
||||
const demandTemplateNoteText = "注:调研维度:战略层(对齐高层对企业长期能力要求)、组织层(各部门业务迭代所需的协作与专业能力)、员工层(个人职业成长技能缺口)。\n" +
|
||||
"注:总务须策划全厂安全培训;\n" +
|
||||
" 品保须策划环境有害物质管理等培训;\n" +
|
||||
" 生产各工段须提供本工段相关的三级安全培训、技能培训等;\n" +
|
||||
"教育训练须涵盖技能、安全、质量、环境、环保、节能等方面。"
|
||||
|
||||
// normalizeDemandTemplateLayout 收集模板版式归一(纯 xlsx 操作,便于单测):
|
||||
// 旧口径文件(内置默认/租户自定义版,F2 为「培訓費用(RMB)」)删除费用列——
|
||||
// RemoveCol(F) 右侧各列整体左移一位(合并单元格/数据验证随列平移),归一为
|
||||
//
|
||||
// A编号 B部门 C课程名称 D适合人员 E地点 F内/外培训 G计划培训月份 H讲师 I备注;
|
||||
//
|
||||
// 新口径文件(F2 已是内/外培训)跳过。返回是否执行了删列。
|
||||
func normalizeDemandTemplateLayout(f *excelize.File, sheet string) bool {
|
||||
if val, _ := f.GetCellValue(sheet, "F2"); !strings.Contains(val, "費用") && !strings.Contains(val, "费用") {
|
||||
return false
|
||||
}
|
||||
_ = f.RemoveCol(sheet, "F")
|
||||
return true
|
||||
}
|
||||
|
||||
// writeDemandNoteColumn 收集模板说明列(纯 xlsx 操作,便于单测):定位表头行
|
||||
// 「备注」列(标准版式 I 列,非标准按表头扫描)右一列,写入调研维度/培训策划
|
||||
// 要求文案并合并至数据区末行(边框+自动换行+顶端对齐)。说明列已被占用或
|
||||
// 自定义模板已带「调研维度」文案时跳过,不覆盖租户内容。
|
||||
func writeDemandNoteColumn(f *excelize.File, sheet string) {
|
||||
noteCol := "J"
|
||||
if val, _ := f.GetCellValue(sheet, "I2"); !strings.Contains(val, "备注") && !strings.Contains(val, "備注") {
|
||||
// 非标准版式:按表头行扫描「备注」列,说明列取其右一列
|
||||
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"} {
|
||||
if val, _ := f.GetCellValue(sheet, col+"2"); strings.Contains(val, "备注") || strings.Contains(val, "備注") {
|
||||
idx, _ := excelize.ColumnNameToNumber(col)
|
||||
noteCol, _ = excelize.ColumnNumberToName(idx + 1)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for r := 1; r <= 3; r++ {
|
||||
val, _ := f.GetCellValue(sheet, noteCol+strconv.Itoa(r))
|
||||
if strings.Contains(val, "调研维度") || strings.TrimSpace(val) != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 合并至数据区末行(内置模板编号 1~12 + 带边框空行,数据区为 4~22 行;
|
||||
// 自定义模板版式差异时同样取 2~22 行为说明块,可预期、不随行数放大)。
|
||||
const noteLastRow = 22
|
||||
_ = f.SetCellValue(sheet, noteCol+"2", demandTemplateNoteText)
|
||||
_ = f.MergeCell(sheet, noteCol+"2", fmt.Sprintf("%s%d", noteCol, noteLastRow))
|
||||
styleID, err := f.NewStyle(&excelize.Style{
|
||||
Alignment: &excelize.Alignment{WrapText: true, Vertical: "top", Horizontal: "left"},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Style: 1, Color: "000000"},
|
||||
{Type: "right", Style: 1, Color: "000000"},
|
||||
{Type: "top", Style: 1, Color: "000000"},
|
||||
{Type: "bottom", Style: 1, Color: "000000"},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
_ = f.SetCellStyle(sheet, noteCol+"2", fmt.Sprintf("%s%d", noteCol, noteLastRow), styleID)
|
||||
}
|
||||
_ = f.SetColWidth(sheet, noteCol, noteCol, 45)
|
||||
}
|
||||
|
||||
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)动态注入:
|
||||
// - 版式归一(2026-11 调整):旧口径含「培训费用(RMB)」列的先删列(右侧列左移),
|
||||
// 归一为 A编号 B部门 C课程名称 D适合人员 E地点 F内/外培训 G计划培训月份
|
||||
// H讲师 I备注;备注(J)右侧写调研维度/培训策划说明列(writeDemandNoteColumn);
|
||||
// - 标题年份改为下一年度(收集模板面向下年度计划,如 2026 年下载即 2027);
|
||||
// - 「计划培训时间」(H 列)表头改为「计划培训月份」,下拉=1~12 月;
|
||||
// - 「计划培训时间」(G 列)表头改为「计划培训月份」,下拉=1~12 月;
|
||||
// - 「参加人员」(D 列)表头归一为「适合人员」(000154 新口径,兼容旧自定义模板);
|
||||
// - 「內/外培訓」(G 列)表头归一为「内/外培训」,下拉=内部/外部;
|
||||
// - 「內/外培訓」(F 列)表头归一为「内/外培训」,下拉=内部/外部;
|
||||
// - 「课程名称」(C 列)下拉按 B 列所选部门联动(OFFSET+MATCH 引用课程查找表,
|
||||
// 仅列该部门课程;非阻断式,也可直接填写新课程);
|
||||
// - 「适合人员」(D 列)「讲师」(I 列)按所选课程 VLOOKUP 自动带出(可改写,
|
||||
// 改后按填写值导入);I 列同时保留员工档案人员下拉;
|
||||
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(I 列)下拉=员工档案人员姓名
|
||||
// - 「适合人员」(D 列)「讲师」(H 列)按所选课程 VLOOKUP 自动带出(可改写,
|
||||
// 改后按填写值导入);H 列同时保留员工档案人员下拉;
|
||||
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(H 列)下拉=员工档案人员姓名
|
||||
// (联查 users 优先取 display_name 真实姓名,回退 username 工号;去重去空)。
|
||||
//
|
||||
// 取值写入同表隐藏辅助列(CA/CC + 课程查找表 CE~CH),以数据验证/公式呈现
|
||||
@@ -149,8 +217,13 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
sheet := sheets[0]
|
||||
|
||||
// 版式归一(2026-11 模板调整):旧口径含「培训费用(RMB)」列的文件先删列,
|
||||
// 之后所有列引用按新口径 A编号 B部门 C课程名称 D适合人员 E地点
|
||||
// F内/外培训 G计划培训月份 H讲师 I备注(备注右侧说明列见 writeDemandNoteColumn)。
|
||||
normalizeDemandTemplateLayout(f, sheet)
|
||||
|
||||
// 标题年份:面向下一年度收集(2026 年打开即 2027 年度教育训练需求表)。
|
||||
// 标题合并于 B1:J1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
|
||||
// 标题合并于 B1:I1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
|
||||
nextYear := time.Now().Year() + 1
|
||||
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"} {
|
||||
val, _ := f.GetCellValue(sheet, col+"1")
|
||||
@@ -161,18 +234,18 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训时间」表头改「计划培训月份」(H2 合并单元格左上角取值)。
|
||||
if val, _ := f.GetCellValue(sheet, "H2"); strings.Contains(val, "计划培训时间") {
|
||||
_ = f.SetCellValue(sheet, "H2", "计划培训月份")
|
||||
// 「计划培训时间」表头改「计划培训月份」(G2 合并单元格左上角取值)。
|
||||
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "计划培训时间") {
|
||||
_ = f.SetCellValue(sheet, "G2", "计划培训月份")
|
||||
}
|
||||
|
||||
// 表头归一(000154,兼容旧版自定义模板):「参加人员」D2 → 「适合人员」,
|
||||
// 「內/外培訓」G2 → 「内/外培训」(繁体转简体+新文案)。
|
||||
// 「內/外培訓」F2 → 「内/外培训」(繁体转简体+新文案)。
|
||||
if val, _ := f.GetCellValue(sheet, "D2"); strings.Contains(val, "参加人员") {
|
||||
_ = f.SetCellValue(sheet, "D2", "适合人员")
|
||||
}
|
||||
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
|
||||
_ = f.SetCellValue(sheet, "G2", "内/外培训")
|
||||
if val, _ := f.GetCellValue(sheet, "F2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
|
||||
_ = f.SetCellValue(sheet, "F2", "内/外培训")
|
||||
}
|
||||
|
||||
// 下拉取值:组织架构部门 + 课程管理课程 + 员工档案人员(去重、去空)
|
||||
@@ -237,10 +310,11 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
// (含历史版本注入的),避免叠加。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("D4:D%d", demandTargetRows+3))
|
||||
|
||||
// 「内/外培训」(G 列)先清既有验证再挂固定下拉,避免旧版模板叠加重复下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
// 「课程名称」(C 列)清既有验证(历史版本注入过扁平课程下拉),换部门联动下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("C4:C%d", demandTargetRows+3))
|
||||
// 清既有验证(兼容租户上传过带验证的自定义模板与历史注入):
|
||||
// C 课程名称 / F 内外培训 / G 计划培训月份 / H 讲师,再统一重挂,避免叠加重复下拉。
|
||||
for _, col := range []string{"C", "F", "G", "H"} {
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s4:%s%d", col, col, demandTargetRows+3))
|
||||
}
|
||||
|
||||
// 写隐藏辅助列并以数据验证下拉挂到对应列。
|
||||
// 下拉为非阻断式(ShowErrorMessage=false,NewDataValidation 默认):单元格可
|
||||
@@ -271,11 +345,11 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
applyList(demandOptColDept, "部门(组织架构)", deptNames, fmt.Sprintf("B4:B%d", demandTargetRows+3), "")
|
||||
applyList(demandOptColLect, "培训讲师(员工档案)", empNames,
|
||||
fmt.Sprintf("I4:I%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
fmt.Sprintf("H4:H%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
|
||||
// 课程联动(000156):查找表写 CE~CH 隐藏列后——
|
||||
// C 列下拉 = OFFSET+MATCH 按 B 列所选部门联动该部门课程(同部门课程连续分组);
|
||||
// D 列 = VLOOKUP 带出课程「适合人员」,I 列 = 带出「讲师」;单元格可改写,
|
||||
// D 列 = VLOOKUP 带出课程「适合人员」,H 列 = 带出「讲师」;单元格可改写,
|
||||
// 改写后按填写值导入(导入解析取单元格显示值)。
|
||||
if n := len(courseRows); n > 0 {
|
||||
last := n + 1 // 查找表数据末行(表头占第 1 行)
|
||||
@@ -308,34 +382,37 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
)
|
||||
dvCourse.SetInput("课程名称(按部门联动)", "先选部门,课程名称下拉即列出该部门课程;也可直接填写新课程")
|
||||
_ = f.AddDataValidation(sheet, dvCourse)
|
||||
// D/I 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
|
||||
// D/H 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
|
||||
for i := 0; i < demandTargetRows; i++ {
|
||||
r := i + 4
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("D%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,3,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("I%d", r),
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("H%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,4,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训月份」(H 列)下拉=1~12(内联列表,非阻断式可自由填写)。
|
||||
// 「计划培训月份」(G 列)下拉=1~12(内联列表,非阻断式可自由填写)。
|
||||
dv := excelize.NewDataValidation(true)
|
||||
dv.SetSqref(fmt.Sprintf("H4:H%d", demandTargetRows+3))
|
||||
dv.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
dv.Type = "list"
|
||||
dv.Formula1 = `"1,2,3,4,5,6,7,8,9,10,11,12"`
|
||||
dv.SetInput("计划培训月份", "从下拉选择 1~12 月;导入后自动按「标题年份-月份」入库(如 2027-1)")
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
|
||||
// 「内/外培训」(G 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
|
||||
// 「内/外培训」(F 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
|
||||
dvTrain := excelize.NewDataValidation(true)
|
||||
dvTrain.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
dvTrain.SetSqref(fmt.Sprintf("F4:F%d", demandTargetRows+3))
|
||||
dvTrain.Type = "list"
|
||||
dvTrain.Formula1 = `"内部,外部"`
|
||||
dvTrain.SetInput("内/外培训", "从下拉选择内部或外部;留空视为未选择")
|
||||
_ = f.AddDataValidation(sheet, dvTrain)
|
||||
|
||||
// 备注(I)右侧说明列:调研维度 + 各部门培训策划要求(2026-11 模板调整)。
|
||||
writeDemandNoteColumn(f, sheet)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return base
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"academy/internal/assets/trainingtemplates"
|
||||
)
|
||||
|
||||
// 收集模板版式归一 + 说明列(2026-11 模板调整,normalizeDemandTemplateLayout /
|
||||
// writeDemandNoteColumn 的纯 xlsx 行为):旧口径文件删「培训费用」列后右侧
|
||||
// 整体左移,备注右侧写调研维度/培训策划说明列(合并至数据区末行)。
|
||||
func TestNormalizeDemandTemplateLayoutAndNoteColumn(t *testing.T) {
|
||||
data, err := trainingtemplates.Default("demand_collection")
|
||||
require.NoError(t, err)
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
sheet := f.GetSheetList()[0]
|
||||
|
||||
// 旧口径:F2 = 培訓費用(RMB)
|
||||
v, _ := f.GetCellValue(sheet, "F2")
|
||||
require.Contains(t, v, "費用")
|
||||
|
||||
require.True(t, normalizeDemandTemplateLayout(f, sheet))
|
||||
// 删列后归一:F=内/外培训(繁简口径均可) G=计划培训时间(下载时再归一文案)
|
||||
// H=讲师 I=备注
|
||||
v, _ = f.GetCellValue(sheet, "F2")
|
||||
require.True(t, strings.Contains(v, "培训") || strings.Contains(v, "培訓"), "F2 应为内/外培训列,实际 %q", v)
|
||||
v, _ = f.GetCellValue(sheet, "G2")
|
||||
require.Contains(t, v, "计划培训时间")
|
||||
v, _ = f.GetCellValue(sheet, "H2")
|
||||
require.Contains(t, v, "讲师")
|
||||
v, _ = f.GetCellValue(sheet, "I2")
|
||||
require.Contains(t, v, "备注")
|
||||
// 已是新口径:F2 不再是费用列,不重复删列
|
||||
require.False(t, normalizeDemandTemplateLayout(f, sheet))
|
||||
|
||||
// 合并单元格/数据验证随删列平移:标题 B1:J1 → B1:I1,
|
||||
// 内置「内/外培训」下拉 G4:G503 → F4:F503(新口径的内/外培训列位)
|
||||
merges, err := f.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
titleMerged := false
|
||||
for _, m := range merges {
|
||||
if m.GetStartAxis() == sheet+"!B1" || m.GetStartAxis() == "B1" {
|
||||
titleMerged = true
|
||||
require.Equal(t, "I1", m.GetEndAxis())
|
||||
}
|
||||
}
|
||||
require.True(t, titleMerged)
|
||||
dvs, err := f.GetDataValidations(sheet)
|
||||
require.NoError(t, err)
|
||||
trainDv := false
|
||||
for _, dvObj := range dvs {
|
||||
if dvObj.Sqref == "F4:F503" {
|
||||
trainDv = true
|
||||
}
|
||||
}
|
||||
require.True(t, trainDv, "内置内外培训下拉应平移至 F4:F503")
|
||||
|
||||
writeDemandNoteColumn(f, sheet)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
f2, err := excelize.OpenReader(bytes.NewReader(buf.Bytes()))
|
||||
require.NoError(t, err)
|
||||
defer f2.Close()
|
||||
|
||||
// 说明列:J2 写入调研维度/培训策划要求文案,合并至数据区末行(数据区 4~22 行)
|
||||
v, _ = f2.GetCellValue(sheet, "J2")
|
||||
require.Contains(t, v, "调研维度")
|
||||
require.Contains(t, v, "战略层")
|
||||
require.Contains(t, v, "总务须策划全厂安全培训")
|
||||
require.Contains(t, v, "教育训练须涵盖技能、安全、质量、环境、环保、节能等方面")
|
||||
noteMerges, err := f2.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
noteMerged := false
|
||||
for _, m := range noteMerges {
|
||||
if m.GetStartAxis() == sheet+"!J2" || m.GetStartAxis() == "J2" {
|
||||
noteMerged = true
|
||||
require.Equal(t, "J22", m.GetEndAxis())
|
||||
}
|
||||
}
|
||||
require.True(t, noteMerged)
|
||||
|
||||
// 重复写入跳过:说明列已占用,不覆盖(合并数保持不变)
|
||||
writeDemandNoteColumn(f2, sheet)
|
||||
merges2, err := f2.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, merges2, len(noteMerges))
|
||||
v, _ = f2.GetCellValue(sheet, "J2")
|
||||
require.Contains(t, v, "调研维度")
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func (h *Handler) requireRoles(c *gin.Context, allowed ...string) (ok bool) {
|
||||
labelParts = append(labelParts, want)
|
||||
}
|
||||
}
|
||||
_ = c.Error(errors.NewForbiddenError("无权执行该操作,需要职称角色: "+strings.Join(labelParts, "/")))
|
||||
_ = c.Error(errors.NewForbiddenError("无权执行该操作,需要职称角色: " + strings.Join(labelParts, "/")))
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -423,10 +423,10 @@ type saveDemandRequest struct {
|
||||
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效)。
|
||||
LecturerExternal string `json:"lecturer_external"`
|
||||
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
|
||||
TrainType string `json:"train_type"`
|
||||
TargetCount int `json:"target_count"`
|
||||
Hours float64 `json:"hours"`
|
||||
ExpectMonth int `json:"expect_month"`
|
||||
TrainType string `json:"train_type"`
|
||||
TargetCount int `json:"target_count"`
|
||||
Hours float64 `json:"hours"`
|
||||
ExpectMonth int `json:"expect_month"`
|
||||
// PlannedTime 计划培训时间(YYYY-MM-DD HH:mm 或 YYYY-MM-DD,选填;确认后同步课程)。
|
||||
PlannedTime string `json:"planned_time"`
|
||||
Remark string `json:"remark"`
|
||||
@@ -735,7 +735,7 @@ func (h *Handler) syncDemandParticipants(ctx context.Context, tenantID uint64, c
|
||||
if startAt := parseFlexibleTime(demand.PlannedTime); startAt != nil {
|
||||
session.StartAt = startAt
|
||||
if demand.Hours > 0 {
|
||||
end := startAt.Add(time.Duration(demand.Hours*float64(time.Hour)))
|
||||
end := startAt.Add(time.Duration(demand.Hours * float64(time.Hour)))
|
||||
session.EndAt = &end
|
||||
}
|
||||
}
|
||||
@@ -834,7 +834,7 @@ func (h *Handler) notifyDemandVerify(ctx context.Context, tenantID uint64, deman
|
||||
"%s 新导入 %d 条年度培训需求(课程:%s)。请登录 AIDO → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。",
|
||||
name, len(courses), strings.Join(courses, "、"),
|
||||
)
|
||||
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year))
|
||||
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year), "")
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to notify dept managers for demand verify", err)
|
||||
continue
|
||||
@@ -870,7 +870,7 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
|
||||
"%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:AIDO → 企业培训 → 月培训计划。",
|
||||
demand.Year, demand.CourseName,
|
||||
)
|
||||
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID); err != nil {
|
||||
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID, ""); err != nil {
|
||||
logger.Error(ctx, "Failed to notify lecturer and supervisors after demand confirm", err)
|
||||
}
|
||||
}
|
||||
@@ -1000,13 +1000,13 @@ func (h *Handler) ListMonthPlans(c *gin.Context) {
|
||||
|
||||
// saveMonthPlanRequest is the body of POST /training/month-plans.
|
||||
type saveMonthPlanRequest struct {
|
||||
ID string `json:"id"`
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
DeptID string `json:"dept_id"`
|
||||
Title string `json:"title" binding:"required"`
|
||||
StartAt string `json:"start_at"` // RFC3339 / "2006-01-02 15:04"
|
||||
Location string `json:"location"`
|
||||
ID string `json:"id"`
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
DeptID string `json:"dept_id"`
|
||||
Title string `json:"title" binding:"required"`
|
||||
StartAt string `json:"start_at"` // RFC3339 / "2006-01-02 15:04"
|
||||
Location string `json:"location"`
|
||||
LecturerID string `json:"lecturer_id"`
|
||||
}
|
||||
|
||||
@@ -1123,23 +1123,23 @@ func (h *Handler) GetCourse(c *gin.Context) {
|
||||
|
||||
// saveCourseRequest is the body of POST /training/courses.
|
||||
type saveCourseRequest struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Mode string `json:"mode"`
|
||||
Type string `json:"type"`
|
||||
LecturerID string `json:"lecturer_id"`
|
||||
Hours float64 `json:"hours"`
|
||||
Credits float64 `json:"credits"`
|
||||
ExamEnabled bool `json:"exam_enabled"`
|
||||
DeptIDs []string `json:"dept_ids"`
|
||||
PostScope string `json:"post_scope"`
|
||||
Description string `json:"description"`
|
||||
MaterialIDs []string `json:"material_ids"`
|
||||
TeachTime string `json:"teach_time"`
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Mode string `json:"mode"`
|
||||
Type string `json:"type"`
|
||||
LecturerID string `json:"lecturer_id"`
|
||||
Hours float64 `json:"hours"`
|
||||
Credits float64 `json:"credits"`
|
||||
ExamEnabled bool `json:"exam_enabled"`
|
||||
DeptIDs []string `json:"dept_ids"`
|
||||
PostScope string `json:"post_scope"`
|
||||
Description string `json:"description"`
|
||||
MaterialIDs []string `json:"material_ids"`
|
||||
TeachTime string `json:"teach_time"`
|
||||
// PlannedTime 计划培训时间(需求确认同步的课程携带;前端编辑时原样回传保留)。
|
||||
PlannedTime string `json:"planned_time"`
|
||||
QuestionBankID string `json:"question_bank_id"`
|
||||
PlannedTime string `json:"planned_time"`
|
||||
QuestionBankID string `json:"question_bank_id"`
|
||||
// 以下为需求确认同步字段(前端编辑时原样回传保留,防止被零值覆盖)。
|
||||
TrainType string `json:"train_type"`
|
||||
Plant string `json:"plant"`
|
||||
@@ -1632,12 +1632,12 @@ func (h *Handler) GetSignCode(c *gin.Context) {
|
||||
|
||||
// CheckinRequest is the body of POST /training/sign-records/checkin.
|
||||
type CheckinRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
Lat float64 `json:"lat"`
|
||||
Lng float64 `json:"lng"`
|
||||
Channel string `json:"channel"`
|
||||
Token string `json:"token" binding:"required"`
|
||||
Lat float64 `json:"lat"`
|
||||
Lng float64 `json:"lng"`
|
||||
Channel string `json:"channel"`
|
||||
// MemberID 可选:讲师/课长/人事现场代扫码/补录。
|
||||
MemberID string `json:"member_id"`
|
||||
MemberID string `json:"member_id"`
|
||||
}
|
||||
|
||||
// Checkin POST /training/sign-records/checkin — 学员扫码签到(带定位校验);
|
||||
|
||||
@@ -3,6 +3,7 @@ package training
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/filetransport"
|
||||
@@ -21,9 +22,12 @@ import (
|
||||
|
||||
// saveCourseLibraryRequest is the body of POST /training/course-library.
|
||||
type saveCourseLibraryRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
OwnerDeptID string `json:"owner_dept_id"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
OwnerDeptID string `json:"owner_dept_id"`
|
||||
// OwnerDeptName 所属部门名(导入兜底:前端未匹配到部门 id 时只传名,
|
||||
// 服务端按组织架构名册解析;与只读展示列 owner_dept_name 同名字段复用)。
|
||||
OwnerDeptName string `json:"owner_dept_name"`
|
||||
Description string `json:"description"`
|
||||
SuitableMembers string `json:"suitable_members"`
|
||||
Category string `json:"category"`
|
||||
@@ -43,6 +47,7 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
|
||||
ID: req.ID,
|
||||
Name: req.Name,
|
||||
OwnerDeptID: req.OwnerDeptID,
|
||||
OwnerDeptName: req.OwnerDeptName,
|
||||
Description: req.Description,
|
||||
SuitableMembers: req.SuitableMembers,
|
||||
Category: req.Category,
|
||||
@@ -96,15 +101,21 @@ func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// SetCourseLibraryPublishStatus POST /training/course-library/:id/:action
|
||||
// — 课程条目发布/下线(000154;action=publish|offline,人事/课长/讲师)。
|
||||
// 发布后课程进入培训中心「和信课程」目录;下线即从目录撤回。
|
||||
// SetCourseLibraryPublishStatus POST /training/course-library/:id/publish|offline
|
||||
// — 课程条目发布/下线(000154,人事/课长/讲师)。发布后课程进入培训中心
|
||||
// 「和信课程」目录;下线即从目录撤回。动作取值兼容两种路由注册:字面量
|
||||
// /course-library/:id/publish|offline(现网注册,FullPath 末段)与
|
||||
// /course-library/:id/:action 通配(Param),任一命中即执行。
|
||||
func (h *Handler) SetCourseLibraryPublishStatus(c *gin.Context) {
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
|
||||
return
|
||||
}
|
||||
action := c.Param("action")
|
||||
if action == "" {
|
||||
action = path.Base(c.FullPath())
|
||||
}
|
||||
status := ""
|
||||
switch c.Param("action") {
|
||||
switch action {
|
||||
case "publish":
|
||||
status = "published"
|
||||
case "offline":
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -575,6 +576,7 @@ func (h *Handler) MarkNotificationsRead(c *gin.Context) {
|
||||
|
||||
// BroadcastNotification POST /training/notifications/broadcast — 培训运营向指定人员批量推送通知
|
||||
// (收集下年度计划等场景);通知 ref_type 用于前端铃铛点击跳转定位。
|
||||
// link_url 传前端 origin:demand_collect 场景企微消息尾部拼模板下载与详情链接。
|
||||
func (h *Handler) BroadcastNotification(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
|
||||
@@ -587,12 +589,13 @@ func (h *Handler) BroadcastNotification(c *gin.Context) {
|
||||
Content string `json:"content"`
|
||||
RefType string `json:"ref_type"`
|
||||
RefID string `json:"ref_id"`
|
||||
LinkURL string `json:"link_url"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
sent, err := h.svc.BroadcastNotification(ctx, callerTenantID(c), req.UserIDs, req.Scene, req.Title, req.Content, req.RefType, req.RefID)
|
||||
sent, err := h.svc.BroadcastNotification(ctx, callerTenantID(c), req.UserIDs, req.Scene, req.Title, req.Content, req.RefType, req.RefID, req.LinkURL)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
@@ -699,6 +702,29 @@ func (h *Handler) DownloadTrainingTemplate(c *gin.Context) {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
serveTemplateFile(c, data, fileName)
|
||||
}
|
||||
|
||||
// DownloadTrainingTemplateSigned GET /training/templates/signed-file?token=…
|
||||
// — 免登录签名下载(2026-11 需求:企微推送消息内点击即下载教育训练需求表
|
||||
// 模板)。token 为 broadcast 入箱时签发的 HMAC(tenant+模板+过期,20 天),
|
||||
// 租户与模板键均取自 token 载荷,不接受调用方指定;匿名路由(见 noAuthAPI)。
|
||||
func (h *Handler) DownloadTrainingTemplateSigned(c *gin.Context) {
|
||||
payload, err := utils.VerifyTrainingTemplateToken(c.Query("token"))
|
||||
if err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError("下载链接无效或已过期").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
data, fileName, err := h.svc.TrainingTemplateFile(c.Request.Context(), payload.TenantID, payload.TemplateKey)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
serveTemplateFile(c, data, fileName)
|
||||
}
|
||||
|
||||
// serveTemplateFile 模板文件响应(附件下载,中文文件名 RFC 5987 透传)。
|
||||
func serveTemplateFile(c *gin.Context, data []byte, fileName string) {
|
||||
contentType := "application/octet-stream"
|
||||
if ct, ok := templateContentTypes[templateExtOf(fileName)]; ok {
|
||||
contentType = ct
|
||||
|
||||
@@ -58,6 +58,12 @@ var noAuthAPI = map[string][]string{
|
||||
// is authenticated by the opaque, single-use `state` parameter instead.
|
||||
"/api/v1/mcp-oauth/callback": {"GET"},
|
||||
"/api/v1/auth/refresh": {"POST"},
|
||||
// Training template signed download (000155): the WeCom demand-collect
|
||||
// markdown footer links here; the recipient clicks it from WeCom without a
|
||||
// browser session. Authenticated by the HMAC token in the query (tenant +
|
||||
// template key + 20-day expiry), never by caller-supplied ids. HEAD is
|
||||
// allowed for the same preview-validation reason as /files/presigned.
|
||||
"/api/v1/training/templates/signed-file": {"GET", "HEAD"},
|
||||
// IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request
|
||||
// before GET to validate Content-Type / Content-Length when rendering
|
||||
// image previews — both verbs must be allowed for image links to work.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"academy/internal/handler/training"
|
||||
"academy/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -16,6 +19,11 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
// templates/signed-file 模板匿名签名下载(2026-11 需求:企微推送消息内点击
|
||||
// 直接下载教育训练需求表模板)。HMAC token 鉴权,不走 Viewer 登录守卫,故在
|
||||
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
|
||||
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
|
||||
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
|
||||
trainingGroup := r.Group("/training", g.Viewer())
|
||||
{
|
||||
// ---- 我的档案(角色决定工作台渲染) ----
|
||||
|
||||
@@ -448,7 +448,10 @@ type TrainingService interface {
|
||||
Notify(ctx context.Context, tenantID uint64, targetUserID, scene, title, content, refType, refID string) error
|
||||
// BroadcastNotification 向指定平台用户批量推送同一条通知(收集下年度计划等
|
||||
// 运营场景):站内流水 + 企微外箱(推送开关开启时 pending,调度器消费)。
|
||||
BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID string) (int, error)
|
||||
// linkURL 为前端 origin(可空,配置中心 notify_link_base_url 优先):
|
||||
// demand_collect 场景据此生成模板匿名下载签名 token 落库,企微消息尾部由
|
||||
// 调度器拼「下载模板/查看详情」链接。
|
||||
BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID, linkURL string) (int, error)
|
||||
|
||||
// ---- 推送管理(2026-11 推学员/推讲师需求,配置中心可观测) ----
|
||||
// NotifySessionStudents 手动对场次名单内未通知学员入队企微开课通知
|
||||
|
||||
+30
-15
@@ -359,12 +359,12 @@ const (
|
||||
|
||||
// TrainingDemand 年度需求提报。
|
||||
type TrainingDemand struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
Year int `json:"year" gorm:"not null;index"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
Year int `json:"year" gorm:"not null;index"`
|
||||
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
DeptID string `json:"dept_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"`
|
||||
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
|
||||
@@ -393,6 +393,8 @@ type TrainingDemand struct {
|
||||
// DeptName/LecturerName 展示字段(联查只读,不落库)。
|
||||
DeptName string `json:"dept_name" gorm:"->"`
|
||||
LecturerName string `json:"lecturer_name" gorm:"->"`
|
||||
// SubmitterName 创建人姓名(提报人,联查 users 只读;年培训计划「创建人」列展示)。
|
||||
SubmitterName string `json:"submitter_name" gorm:"->"`
|
||||
}
|
||||
|
||||
// TableName pins the physical table name.
|
||||
@@ -612,6 +614,8 @@ type TrainingCourseLibrary struct {
|
||||
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
|
||||
// LecturerName 讲师姓名(联查 users 只读,不落库)。
|
||||
LecturerName string `json:"lecturer_name" gorm:"->"`
|
||||
// CreatorName 创建人姓名(联查 users 只读,不落库;列表「创建人」列展示)。
|
||||
CreatorName string `json:"creator_name" gorm:"->"`
|
||||
// OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。
|
||||
OwnerDeptName string `json:"owner_dept_name" gorm:"->"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
@@ -802,7 +806,7 @@ type TrainingQuestionBank struct {
|
||||
Code string `json:"code" gorm:"type:varchar(32);default:''"`
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
// LibraryCourseID 课程管理条目 id(试题随课程管理维护,可与 course_id 并存,000153)。
|
||||
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
|
||||
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
|
||||
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
|
||||
CourseID string `json:"course_id" gorm:"type:varchar(36);default:''"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
|
||||
@@ -1167,6 +1171,12 @@ const (
|
||||
// SceneRemindMonthlyLecturer 每周一 09:00(北京时间)对当月仍有未结束
|
||||
// 场次的讲师发送汇总提醒;场次全部结束即停推(收件人查询自然过滤)。
|
||||
SceneRemindMonthlyLecturer = "remind_monthly_lecturer"
|
||||
// SceneDemandCollect 收集下年度培训需求的运营广播(年培训计划推送);
|
||||
// 通知行可携带 LinkURL/LinkToken,企微消息尾部拼模板下载与详情链接。
|
||||
SceneDemandCollect = "demand_collect"
|
||||
// RefTypePlan marks notifications whose ref_id is a plan year (e.g. 2027);
|
||||
// 前端铃铛点击 ref_type=plan 跳转年培训计划页。
|
||||
RefTypePlan = "plan"
|
||||
)
|
||||
|
||||
// TrainingRemindScene builds the scene key of a T-N days session reminder.
|
||||
@@ -1181,15 +1191,20 @@ func TrainingRemindScene(days int, lecturer bool) string {
|
||||
// PushStatus 家族是企微主动推送的 outbox 状态:空 = 无需企微推送,
|
||||
// pending 由 training scheduler 投递(sending/sent/skipped/dead)。
|
||||
type TrainingNotification struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
TargetUserID string `json:"target_user_id" gorm:"type:varchar(36);not null;index"`
|
||||
Channel string `json:"channel" gorm:"type:varchar(16);default:'inapp'"`
|
||||
Scene string `json:"scene" gorm:"type:varchar(64);not null"`
|
||||
Title string `json:"title" gorm:"type:varchar(255);default:''"`
|
||||
Content string `json:"content" gorm:"type:text;default:''"`
|
||||
RefType string `json:"ref_type" gorm:"type:varchar(32);default:''"`
|
||||
RefID string `json:"ref_id" gorm:"type:varchar(64);default:''"`
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
TargetUserID string `json:"target_user_id" gorm:"type:varchar(36);not null;index"`
|
||||
Channel string `json:"channel" gorm:"type:varchar(16);default:'inapp'"`
|
||||
Scene string `json:"scene" gorm:"type:varchar(64);not null"`
|
||||
Title string `json:"title" gorm:"type:varchar(255);default:''"`
|
||||
Content string `json:"content" gorm:"type:text;default:''"`
|
||||
RefType string `json:"ref_type" gorm:"type:varchar(32);default:''"`
|
||||
RefID string `json:"ref_id" gorm:"type:varchar(64);default:''"`
|
||||
// LinkURL 前端 origin(broadcast 调用方传入),企微外箱据此拼 markdown
|
||||
// 尾部链接(详情页/模板签名下载);空 = 不拼。000155。
|
||||
LinkURL string `json:"link_url" gorm:"type:varchar(512);default:''"`
|
||||
// LinkToken 模板匿名下载签名 token(仅 demand_collect 场景生成);空 = 无。
|
||||
LinkToken string `json:"link_token" gorm:"type:varchar(255);default:''"`
|
||||
SentAt time.Time `json:"sent_at"`
|
||||
ReadAt *time.Time `json:"read_at"`
|
||||
PushStatus string `json:"push_status" gorm:"type:varchar(16);default:''"`
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TrainingTemplateTokenValidity 签名下载链接有效期(2026-11 需求:默认 20 天,
|
||||
// 覆盖一次年度需求收集窗口;过期后链接失效,需重新推送)。
|
||||
const TrainingTemplateTokenValidity = 20 * 24 * time.Hour
|
||||
|
||||
// TrainingTemplateSignedFilePath 匿名签名下载路由路径;企微 footer 链接、
|
||||
// 路由注册与 noAuthAPI 白名单三方共用,防路径漂移。
|
||||
const TrainingTemplateSignedFilePath = "/api/v1/training/templates/signed-file"
|
||||
|
||||
// TrainingTemplateTokenPayload is the signed anonymous download token carried
|
||||
// in the WeCom markdown footer of a demand-collect broadcast. The signature
|
||||
// binds tenant + template key + expiry so a leaked URL can only fetch one
|
||||
// blank template of one tenant and dies with the collection window.
|
||||
type TrainingTemplateTokenPayload struct {
|
||||
TenantID uint64 `json:"tid"`
|
||||
TemplateKey string `json:"key"`
|
||||
ExpiresAt int64 `json:"exp"`
|
||||
}
|
||||
|
||||
var (
|
||||
templateTokenSecretOnce sync.Once
|
||||
templateTokenSecret string
|
||||
)
|
||||
|
||||
// trainingTemplateTokenSigningKey mirrors oidcStateSigningKey: dedicated env
|
||||
// first, JWT_SECRET fallback, per-process random as last resort (tokens then
|
||||
// die on restart — acceptable for dev; production sets JWT_SECRET).
|
||||
func trainingTemplateTokenSigningKey() string {
|
||||
templateTokenSecretOnce.Do(func() {
|
||||
if envSecret := strings.TrimSpace(os.Getenv("TRAINING_TEMPLATE_TOKEN_SECRET")); envSecret != "" {
|
||||
templateTokenSecret = envSecret
|
||||
return
|
||||
}
|
||||
if envSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")); envSecret != "" {
|
||||
templateTokenSecret = envSecret
|
||||
return
|
||||
}
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
panic(fmt.Sprintf("failed to generate training template token signing key: %v", err))
|
||||
}
|
||||
templateTokenSecret = base64.StdEncoding.EncodeToString(randomBytes)
|
||||
})
|
||||
return templateTokenSecret
|
||||
}
|
||||
|
||||
// SignTrainingTemplateToken returns a tamper-evident download token:
|
||||
// base64url(payload).base64url(hmac). ExpiresAt zero = now + default validity.
|
||||
func SignTrainingTemplateToken(payload *TrainingTemplateTokenPayload) (string, error) {
|
||||
if payload == nil {
|
||||
return "", errors.New("training template token payload is required")
|
||||
}
|
||||
if payload.TenantID == 0 {
|
||||
return "", errors.New("training template token tenant is required")
|
||||
}
|
||||
if strings.TrimSpace(payload.TemplateKey) == "" {
|
||||
return "", errors.New("training template token key is required")
|
||||
}
|
||||
if payload.ExpiresAt == 0 {
|
||||
payload.ExpiresAt = time.Now().Add(TrainingTemplateTokenValidity).Unix()
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal training template token: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(trainingTemplateTokenSigningKey()))
|
||||
mac.Write(raw)
|
||||
sig := mac.Sum(nil)
|
||||
return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
||||
}
|
||||
|
||||
// VerifyTrainingTemplateToken validates the HMAC and expiry of a token and
|
||||
// returns its payload for the anonymous download endpoint.
|
||||
func VerifyTrainingTemplateToken(raw string) (*TrainingTemplateTokenPayload, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
parts := strings.Split(raw, ".")
|
||||
if len(parts) != 2 {
|
||||
return nil, errors.New("invalid training template token format")
|
||||
}
|
||||
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode training template token payload: %w", err)
|
||||
}
|
||||
sigBytes, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode training template token signature: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(trainingTemplateTokenSigningKey()))
|
||||
mac.Write(payloadBytes)
|
||||
if !hmac.Equal(mac.Sum(nil), sigBytes) {
|
||||
return nil, errors.New("training template token signature mismatch")
|
||||
}
|
||||
var payload TrainingTemplateTokenPayload
|
||||
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal training template token: %w", err)
|
||||
}
|
||||
if payload.TenantID == 0 || strings.TrimSpace(payload.TemplateKey) == "" {
|
||||
return nil, errors.New("training template token tenant/key is required")
|
||||
}
|
||||
if time.Now().Unix() > payload.ExpiresAt {
|
||||
return nil, errors.New("training template token expired")
|
||||
}
|
||||
return &payload, nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTrainingTemplateTokenRoundTrip(t *testing.T) {
|
||||
token, err := SignTrainingTemplateToken(&TrainingTemplateTokenPayload{
|
||||
TenantID: 42,
|
||||
TemplateKey: "demand_collection",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, token)
|
||||
|
||||
payload, err := VerifyTrainingTemplateToken(token)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(42), payload.TenantID)
|
||||
require.Equal(t, "demand_collection", payload.TemplateKey)
|
||||
|
||||
// 默认有效期 = 20 天(2026-11 需求)
|
||||
until := time.Unix(payload.ExpiresAt, 0)
|
||||
require.WithinDuration(t, time.Now().Add(TrainingTemplateTokenValidity), until, 2*time.Minute)
|
||||
}
|
||||
|
||||
func TestTrainingTemplateTokenExplicitExpiry(t *testing.T) {
|
||||
expiry := time.Now().Add(-time.Hour).Unix() // 已过期
|
||||
token, err := SignTrainingTemplateToken(&TrainingTemplateTokenPayload{
|
||||
TenantID: 42, TemplateKey: "demand_collection", ExpiresAt: expiry,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = VerifyTrainingTemplateToken(token)
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "expired")
|
||||
}
|
||||
|
||||
func TestTrainingTemplateTokenTamperRejected(t *testing.T) {
|
||||
token, err := SignTrainingTemplateToken(&TrainingTemplateTokenPayload{
|
||||
TenantID: 42, TemplateKey: "demand_collection",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 篡改签名段
|
||||
tampered := token[:len(token)-4] + "AAAA"
|
||||
_, err = VerifyTrainingTemplateToken(tampered)
|
||||
require.Error(t, err)
|
||||
|
||||
// 篡改载荷段(换租户)
|
||||
parts := strings.Split(token, ".")
|
||||
require.Len(t, parts, 2)
|
||||
_, err = VerifyTrainingTemplateToken(strings.ToUpper(parts[0]) + "." + parts[1])
|
||||
require.Error(t, err)
|
||||
|
||||
// 空载荷字段
|
||||
_, err = SignTrainingTemplateToken(&TrainingTemplateTokenPayload{TemplateKey: "demand_collection"})
|
||||
require.Error(t, err)
|
||||
_, err = SignTrainingTemplateToken(&TrainingTemplateTokenPayload{TenantID: 42})
|
||||
require.Error(t, err)
|
||||
_, err = SignTrainingTemplateToken(nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Migration: 000155_training_notification_link (down)
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000155] Dropping notification deep-link columns...'; END $$;
|
||||
|
||||
ALTER TABLE tr_notifications
|
||||
DROP COLUMN IF EXISTS link_url,
|
||||
DROP COLUMN IF EXISTS link_token;
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Migration: 000155_training_notification_link
|
||||
-- Demand-collect broadcast deep links (2026-11 requirement: push the annual
|
||||
-- plan collection notice with a click-to-download template link and a
|
||||
-- "view more details" entry into the training system).
|
||||
-- 1) tr_notifications.link_url stores the frontend origin supplied by the
|
||||
-- broadcast caller (window.location.origin); the WeCom outbox consumer
|
||||
-- composes the markdown footer from it at dispatch time. Empty = no footer.
|
||||
-- 2) tr_notifications.link_token stores the HMAC-signed anonymous download
|
||||
-- token for the demand_collection template (signed-file endpoint; 20-day
|
||||
-- validity). Empty = no template line.
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000155] Adding notification deep-link columns...'; END $$;
|
||||
|
||||
ALTER TABLE tr_notifications
|
||||
ADD COLUMN IF NOT EXISTS link_url VARCHAR(512) NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS link_token VARCHAR(255) NOT NULL DEFAULT '';
|
||||
|
||||
COMMENT ON COLUMN tr_notifications.link_url IS 'Frontend origin for WeCom markdown footer links (details page / signed template download); empty = no footer';
|
||||
COMMENT ON COLUMN tr_notifications.link_token IS 'HMAC-signed anonymous download token for the demand_collection template; empty = none';
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# air 热重载构建脚本(.air.toml Build.Cmd 调用)。
|
||||
# Windows 下 air v1.67 经 PowerShell 执行 Build.Cmd:不做 bash 命令替换、
|
||||
# 无法执行 .sh,原内联 cmd 的 $(./scripts/get_version.sh ldflags) 会失败;
|
||||
# macOS/Linux 的 /bin/sh -c 同样可用本脚本,构建口径全平台一致。
|
||||
# 产物固定 .exe 后缀(Windows 的 PowerShell 启动非 .exe 文件不识别;
|
||||
# Unix 对扩展名不敏感,同一路径两端通用)。
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
LDFLAGS="$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"
|
||||
# CGO 编译开关:在既有值基础上「追加」告警抑制(duckdb 静态库),不得覆盖——
|
||||
# 环境变量优先级高于 go env -w,直接 export 会丢掉头文件包含路径(如本机
|
||||
# go env -w 持久化的 -I<sqlite3.h> 目录),导致 sqlite-vec 等 CGO 包编译失败。
|
||||
# 因此并集 = go env -w 持久化值 + 继承的环境值 + 追加项(重复项无害)。
|
||||
goenv_file="$(go env GOENV 2>/dev/null || true)"
|
||||
persisted_cflags="$(grep -E '^CGO_CFLAGS=' "$goenv_file" 2>/dev/null | head -1 | cut -d= -f2- | tr -d '"' || true)"
|
||||
export CGO_CFLAGS="${persisted_cflags} ${CGO_CFLAGS:-} -Wno-deprecated-declarations -Wno-gnu-folding-constant"
|
||||
|
||||
mkdir -p ./tmp
|
||||
go build -tags "${GO_BUILD_TAGS:-}" -ldflags="$LDFLAGS" -o ./tmp/main.exe ./cmd/server
|
||||
Reference in new issue
Block a user