feat(training): 推送管理:学员开课通知、周一讲师汇总与企微推送闭环

[2026-11 推学员/推讲师需求] 培训提醒统一走 tr_notifications outbox(站内流水 +
企微 push_status 投递),推送文案可配置,管理端可查逐人投递明细。

后端 internal/application/service:
- training_notify.go(重写)推送管理核心:
  - 学员开课通知 scene=session_notice_student:immediate 场次在名单保存/课件上传后
    立即入队,day_before 场次由调度器 T-1 且课件就绪时入队;课件门控 +
    (tenant,target,scene,ref) 唯一索引幂等,一人一场最多一条
  - 周一讲师未完成汇总 scene=remind_monthly_lecturer:北京时间周一发送(时点可配),
    轮次键 YYYY-MM-Wn 幂等,场次全部结束自然停推
  - 提醒推送文案模板 notify_text_templates:配置中心可编辑,{占位符} 替换渲染,
    空字段回落内置默认
  - ListPushLogs 推送记录:逐人投递明细(push_status/重试/错误 + 员工姓名工号映射)
- training_scheduler.go:
  - 学员提醒收敛到 session_notice_student 单通道,讲师 T-N 授课提醒与
    课程维护提醒(临近开课仍缺课件)保持
  - 新增每周一讲师未完成汇总生成(租户开关 + 发送小时可配)
  - 企微外箱消费 dispatchPending:FOR UPDATE SKIP LOCKED 多实例安全,
    sending 超时回收,重试上限置 dead
  - PushTestNotification 推送链路自测(校验凭据与 userid 绑定)
- training_ops.go:默认规则种子追加企微推送开关键/周一讲师键/提醒文案默认模板

前端 frontend/src/views/training:
- RulePanel.vue:配置中心新增「提醒推送文案」编辑卡与「推送记录」明细表
  (场景筛选、手动触发周一讲师提醒)
- CoursePanel.vue:场次通知模式新增 immediate「名单/课件就绪后立即推送」
- CourseCatalog.vue:「我的课程」角色标记(我主讲/我参加)、最近场次排期排序、
  待维护统计改橙色(与草稿一致)
- MemberPanel.vue:员工档案支持企微账号绑定(培训提醒推送目标)

测试:training_notify_test.go(模板解析/占位符渲染)、training_scheduler_test.go
(生成幂等/课件门控/停推开关/投递结果/测试推送/文案渲染),go test 全部通过。
This commit is contained in:
runny committed 2026-11-16 18:12:35 +08:00
1 parent 7ec21f35b0
commit e378e8b7fd
10 files changed
+11344

No files matched your search

+5586
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,606 @@
<template>
<div class="course-catalog">
<!-- 工具行:范围页签(全部/线上/线下/我的课程) + 搜索 -->
<div class="catalog-toolbar">
<div class="catalog-filter" role="tablist" aria-label="课程范围">
<button
v-for="f in FILTERS"
:key="f.key"
type="button"
role="tab"
:aria-selected="filter === f.key"
class="catalog-filter__item"
:class="{ 'is-active': filter === f.key }"
@click="filter = f.key"
>{{ f.label }}</button>
</div>
<div class="catalog-actions">
<t-input v-model="keyword" class="catalog-search" clearable placeholder="搜索课程 / 课件">
<template #prefixIcon>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
</template>
</t-input>
</div>
</div>
<!-- 汇总行:与设计稿一致(共 N 门 · 线上 / 线下 / 本月新增或课件数)。
待维护 = 我任讲师且未发布(草稿/待审)、或已发布但未上传课件的课程数
(2026-11 需求:>0 时用与「草稿」一致的橙色提醒,不再用红色)。 -->
<div class="catalog-stats">
{{ statsText }}
<span class="catalog-stats__maintain" :class="{ 'is-alert': maintainCount > 0 }">待维护 {{ maintainCount }} 门</span>
</div>
<!-- 课程卡片网格 -->
<t-loading :loading="loading" class="catalog-grid-wrap">
<div class="catalog-grid">
<article v-for="card in visibleCards" :key="card.id" class="course-card" role="link" tabindex="0" @click="openCourse(card)" @keydown.enter="openCourse(card)">
<div class="course-card__cover" :class="card.mode === 'online' ? 'is-online' : 'is-offline'">
<svg v-if="card.mode === 'online'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="12" rx="2"/><path d="m10 8.6 4 2.4-4 2.4z"/><path d="M8 21h8M12 17v4"/></svg>
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 17.5V5a1.6 1.6 0 0 1 1.6-1.6h9A1.6 1.6 0 0 1 16.2 5v12.5"/><path d="M4 17.5A2.5 2.5 0 0 0 6.5 20h9.7"/><path d="M16.2 8.2H19a1.4 1.4 0 0 1 1.4 1.4v3.1a2.3 2.3 0 1 1-4.6 0V9.6"/><path d="M7.5 7h5M7.5 10h5"/></svg>
<span>课程封面</span>
</div>
<div class="course-card__body">
<div class="course-card__tags">
<t-tag :theme="card.mode === 'online' ? 'primary' : 'success'" variant="light" size="small" :class="{ 'course-tag-offline': card.mode !== 'online' }">
{{ card.mode === 'online' ? '线上课程' : '线下课程' }}
</t-tag>
<!-- [2026-11 需求]「我的课程」角色标记:区分我要进行培训(我主讲,橙色)/ 我要参加(蓝绿色)的课程 -->
<t-tag
v-if="card.roleTag"
:theme="card.roleTag === 'teach' ? 'warning' : 'primary'"
variant="light"
size="small"
>{{ card.roleTag === 'teach' ? '我主讲' : '我参加' }}</t-tag>
</div>
<h3 class="course-card__name" :title="card.name">{{ card.name }}</h3>
<p class="course-card__meta" :title="card.meta">{{ card.meta }}</p>
<div class="course-card__foot">
<div class="course-card__bar" :class="card.barClass"><i :style="{ width: card.barWidth }"></i></div>
<span class="course-card__state" :class="card.stateClass">{{ card.state }}</span>
<!-- 我任讲师的课程:直达「培训课程」维护该课(自动打开课程详情弹窗) -->
<button
v-if="card.maintainable"
type="button"
class="course-card__maintain"
@click.stop="goMaintain(card.id)"
>维护课程</button>
</div>
</div>
</article>
</div>
<t-empty v-if="!loading && !visibleCards.length" class="catalog-empty" :description="filter === 'mine' ? '暂无与我相关的课程' : '暂无课程'" />
</t-loading>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
getMyProfile,
listCourses,
listMyLearningTasks,
listSessions,
type LearningTask,
type TrainingCourse,
type TrainingCourseSession,
type TrainingMember,
unwrap,
} from '@/api/training'
const props = defineProps<{ roles: string[]; admin?: boolean }>()
const router = useRouter()
// 卡片点击 → 课程学习详情页(课件在线预览 + 随堂考试);
// 未发布课程(我任讲师的草稿/待审)无学习视角,点击直达维护。
const openCourse = (card: CatalogCard) => {
if (card.unpublished) {
goMaintain(card.id)
return
}
router.push(`/platform/training/course/${card.id}`)
}
// 【维护课程】→ 培训课程页并自动打开该课的课程详情弹窗
const goMaintain = (courseId: string) => {
router.push({ path: '/platform/training/course', query: { courseId } })
}
const loading = ref(false)
const courses = ref<TrainingCourse[]>([])
// 课程维护视角(不带 scope=student)的我名下课程:纯讲师含草稿,供「我的课程」与待维护统计
const lecturerCourses = ref<TrainingCourse[]>([])
const myProfile = ref<TrainingMember | null>(null)
const myTasks = ref<LearningTask[]>([])
const sessions = ref<TrainingCourseSession[]>([])
const FILTERS = [
{ key: 'all', label: '全部课程' },
{ key: 'online', label: '线上课程' },
{ key: 'offline', label: '线下课程' },
{ key: 'mine', label: '我的课程' },
] as const
// 工作台进目录默认落在「我的课程」(2026-11 需求:与我相关的课优先展示)
const filter = ref<string>('mine')
const keyword = ref('')
// 目录页面向全体员工:仅展示已发布课程(草稿/待审在「培训课程」维护)
const publishedCourses = computed(() => courses.value.filter((c) => c.status === 'published'))
const statsText = computed(() => {
const list = publishedCourses.value
const online = list.filter((c) => c.mode === 'online').length
const offline = list.length - online
const now = new Date()
const monthNew = list.filter((c) => {
const raw = (c as unknown as { created_at?: string }).created_at
if (!raw) return false
const d = new Date(raw)
return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth()
}).length
const parts = [`共 ${list.length} 门课程`, `线上 ${online} 门`, `线下 ${offline} 门`]
parts.push(monthNew ? `本月新增 ${monthNew} 门` : `课件 ${list.reduce((n, c) => n + (c.material_ids?.length || 0), 0)} 个`)
return parts.join(' · ')
})
// 我的学习任务索引(course_id → status):线上课程卡片展示我的进度
const myTaskByCourse = computed(() => {
const map = new Map<string, LearningTask>()
myTasks.value.forEach((t) => {
if (!map.has(t.course_id)) map.set(t.course_id, t)
})
return map
})
// 「我的课程」相关性口径(与后端推送口径一致):
// ① 我有该课学习任务(线上必修按部门推送);② 我是该课讲师;
// ③ 课程部门范围覆盖我(dept_ids 为空 = 全员可见,非空需包含我的部门)。
// 讲师匹配用平台用户 id(user_id)——与后端 course.LecturerID == callerUserID 同口径。
const myUserId = computed(() => myProfile.value?.user_id || '')
const isMyTeaching = (c: TrainingCourse) => !!myUserId.value && c.lecturer_id === myUserId.value
const isMyCourse = (c: TrainingCourse) => {
if (myTaskByCourse.value.has(c.id)) return true
if (isMyTeaching(c)) return true
const scope = c.dept_ids || []
if (!scope.length) return true
return !!myProfile.value && scope.includes(myProfile.value.dept_id)
}
// 可进「培训课程」维护页的角色(与 Training.vue canManageTabs 同口径)
const canMaintainCourses = computed(
() => props.admin || props.roles.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r)),
)
// 我任讲师的课程(含未发布):维护视角列表 + 学员视角已发布列表按 id 合并去重。
// 纯讲师/管理角色才请求维护视角;纯学员只能拿到已发布的(后端强制),合并结果不受影响。
const myTeachingCourses = computed<TrainingCourse[]>(() => {
const map = new Map<string, TrainingCourse>()
publishedCourses.value.filter(isMyTeaching).forEach((c) => map.set(c.id, c))
lecturerCourses.value.filter(isMyTeaching).forEach((c) => map.set(c.id, c))
return [...map.values()]
})
// 待维护 = 我任讲师且未发布(草稿/待审)、或已发布但未上传课件的课程
// (线上课发布强制有课件,实际命中的多为线下课:学员通知在课件上传前不会推送)
const needsMaintain = (c: TrainingCourse) => c.status !== 'published' || !c.material_ids?.length
const maintainCount = computed(() => myTeachingCourses.value.filter(needsMaintain).length)
// 线下课排期索引:取最近一场排期/已完成场次汇总
const sessionByCourse = computed(() => {
const map = new Map<string, TrainingCourseSession[]>()
sessions.value.forEach((s) => {
const list = map.get(s.course_id) || []
list.push(s)
map.set(s.course_id, list)
})
return map
})
const typeText = (c: TrainingCourse) => (c.type === 'elective' ? '选修' : '必修')
const fmtMonthDay = (raw: string | null) => {
if (!raw) return ''
const d = new Date(raw)
return `${d.getMonth() + 1}月${d.getDate()}日`
}
// [2026-11 需求] 「我的课程」排序时间锚点:最近场次排期优先,其次授课时间/计划时间/创建时间;
// 月份粒度(YYYY-MM)展开为当月 1 日,无可用时间返回 NaN(排序时落到最后)
const courseTimeMs = (raw?: string | null): number => {
if (!raw) return NaN
const v = /^\d{4}-\d{2}$/.test(raw) ? `${raw}-01` : raw
const t = new Date(v).getTime()
return Number.isFinite(t) ? t : NaN
}
const courseNearestTime = (c: TrainingCourse): number => {
const list = (sessionByCourse.value.get(c.id) || [])
.slice()
.sort((a, b) => String(a.start_at).localeCompare(String(b.start_at)))
const s = list.find((x) => x.status === 'scheduled' && x.start_at) || list.find((x) => x.start_at)
const fallback =
c.teach_time || c.planned_time || (c as unknown as { created_at?: string }).created_at || ''
return courseTimeMs(s?.start_at || fallback)
}
interface CatalogCard {
id: string
name: string
mode: string
meta: string
state: string
stateClass: string
barWidth: string
barClass: string
/** 我任讲师且可进维护页:卡片展示【维护课程】按钮 */
maintainable: boolean
/** 未发布(草稿/待审)的讲师课程:无学习视角,点击直达维护 */
unpublished: boolean
/** [2026-11 需求]「我的课程」角色标记:teach=我主讲 / attend=我参加(其余视图不标记) */
roleTag?: 'teach' | 'attend'
}
// 卡片元信息与底部进度条:
// 线上 = 我的学习任务状态(已完成/学习中/待学习/已逾期),进度条只表达确定状态,不虚构百分比;
// 线下 = 真实排期进度(已完成场次/已排期场次)。
// 未发布的讲师课程(仅「我的课程」视图可见)以草稿/待审态展示。
const visibleCards = computed<CatalogCard[]>(() => {
const kw = keyword.value.trim().toLowerCase()
// 数据源:全部/线上/线下 = 已发布目录;我的课程 = 我相关的已发布课 + 我任讲师的课(含未发布,已发布的按 id 去重)
let source = publishedCourses.value
if (filter.value === 'mine') {
const minePublished = publishedCourses.value.filter(isMyCourse)
const mineIds = new Set(minePublished.map((c) => c.id))
source = [...minePublished, ...myTeachingCourses.value.filter((c) => !mineIds.has(c.id))]
}
let list = source.filter((c) => {
if (filter.value === 'online' && c.mode !== 'online') return false
if (filter.value === 'offline' && c.mode !== 'offline') return false
if (filter.value === 'mine' && !isMyCourse(c) && !isMyTeaching(c)) return false
if (kw && !(c.name.toLowerCase().includes(kw) || (c.tags || []).some((t) => String(t).toLowerCase().includes(kw)))) return false
return true
})
// [2026-11 需求] 「我的课程」排序:待维护(我主讲未发布/缺课件)置顶,
// 其余按与当前时间的邻近度升序(临近开课/结课的在前,无时间锚点的排最后)
if (filter.value === 'mine') {
const now = Date.now()
const dist = (c: TrainingCourse) => {
const t = courseNearestTime(c)
return Number.isFinite(t) ? Math.abs(t - now) : Number.POSITIVE_INFINITY
}
list = list.slice().sort((a, b) => {
const ma = isMyTeaching(a) && needsMaintain(a) ? 0 : 1
const mb = isMyTeaching(b) && needsMaintain(b) ? 0 : 1
if (ma !== mb) return ma - mb
return ma === 0 ? 0 : dist(a) - dist(b)
})
}
return list
.map((c) => {
const head = [c.post_scope, typeText(c), `${c.hours} 学时`, c.exam_enabled ? '随堂考试' : ''].filter(Boolean).join(' · ')
const maintainable = isMyTeaching(c) && canMaintainCourses.value
const unpublished = c.status !== 'published'
// [2026-11 需求]「我的课程」角色标记:我主讲(优先) / 我参加,其余视图不标记
const roleTag = filter.value === 'mine' ? (isMyTeaching(c) ? ('teach' as const) : ('attend' as const)) : undefined
// 未发布讲师课:无学习任务与排期进度,展示草稿/待审 + 计划时间(需求确认同步)
if (unpublished) {
const planText = c.planned_time || (c.teach_time && !/^\d{4}-\d{2}$/.test(c.teach_time) ? c.teach_time : '')
return {
id: c.id,
name: c.name,
mode: c.mode,
meta: `${head}${planText ? ` · 计划 ${fmtMonthDay(planText)}` : ''}`,
state: c.status === 'pending' ? '待审' : '草稿',
stateClass: 'is-warn',
barWidth: '0%',
barClass: '',
maintainable,
unpublished,
roleTag,
}
}
if (c.mode === 'online') {
const task = myTaskByCourse.value.get(c.id)
const status = task?.status || 'pending'
const stateMap: Record<string, { state: string; cls: string }> = {
done: { state: '已完成', cls: 'is-good' },
doing: { state: '学习中', cls: 'is-doing' },
overdue: { state: '已逾期', cls: 'is-bad' },
pending: { state: '待学习', cls: '' },
}
const cur = status === 'done' ? { state: '已完成', cls: 'is-good', width: '100%', bar: 'is-done' }
: status === 'doing' ? { state: '学习中', cls: 'is-doing', width: '100%', bar: 'is-doing-bar' }
: status === 'overdue' ? { state: '已逾期', cls: 'is-bad', width: '0%', bar: '' }
: { state: '待学习', cls: '', width: '0%', bar: '' }
const materials = c.material_ids?.length ? ` · 课件 ${c.material_ids.length} 个` : ''
return { id: c.id, name: c.name, mode: c.mode, meta: `${head}${materials}`, state: cur.state, stateClass: cur.cls, barWidth: cur.width, barClass: cur.bar, maintainable, unpublished, roleTag }
}
const sess = (sessionByCourse.value.get(c.id) || []).sort((a, b) => String(a.start_at).localeCompare(String(b.start_at)))
const finished = sess.filter((s) => s.status === 'finished').length
const next = sess.find((s) => s.status === 'scheduled' && s.start_at)
const scheduleText = next ? `${fmtMonthDay(next.start_at)} ${next.location || '线下授课'}` : finished ? `已完成 ${finished} 场` : '待排期'
const ratio = sess.length ? Math.round((finished / sess.length) * 100) : 0
return {
id: c.id,
name: c.name,
mode: c.mode,
meta: `${head} · ${scheduleText}`,
state: next ? '已排期' : finished ? '已结课' : '待排期',
stateClass: next ? 'is-doing' : finished ? 'is-good' : '',
barWidth: `${ratio}%`,
barClass: ratio >= 100 ? 'is-done' : '',
maintainable,
unpublished,
roleTag,
}
})
})
const loadAll = async () => {
loading.value = true
try {
// 讲师/管理角色额外拉维护视角课程(纯讲师=自己名下含草稿;管理=全部,下方按讲师 id 过滤),
// 供「我的课程」展示我主讲(含未发布)课程与「待维护」统计;纯学员无此视角,跳过。
const needMaintainView = props.admin || props.roles.some((r) => ['hr', 'supervisor', 'exec', 'lecturer'].includes(r))
const [c, t, s, me, lc] = await Promise.all([
// 学员目录视图:scope=student 统一走已发布课程口径(讲师账号的学习视角不受课程维护范围影响)
listCourses({ page_size: 100, scope: 'student' }),
listMyLearningTasks().catch(() => null),
listSessions({ year: 0, month: 0, scope: 'student' }).catch(() => null),
getMyProfile().catch(() => null),
needMaintainView ? listCourses({ page_size: 100 }).catch(() => null) : Promise.resolve(null),
])
courses.value = unwrap(c)?.items || []
myTasks.value = (t && unwrap(t)) || []
sessions.value = (s && unwrap(s)) || []
myProfile.value = (me && unwrap(me)) || null
lecturerCourses.value = (lc && unwrap(lc)?.items) || []
} finally {
loading.value = false
}
}
onMounted(loadAll)
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.catalog-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--app-space-4);
margin-bottom: 8px;
flex-wrap: wrap;
}
.catalog-filter {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
&__item {
height: 32px;
padding: 0 14px;
border: 1px solid transparent;
border-radius: var(--app-radius-md);
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-md);
cursor: pointer;
transition: all var(--app-motion-fast) ease;
&:hover {
color: var(--td-text-color-primary);
}
&.is-active {
border-color: var(--td-component-border);
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
font-weight: 600;
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: -2px;
}
}
}
.catalog-actions {
display: flex;
align-items: center;
gap: 8px;
}
.catalog-search {
width: 220px;
svg {
width: 16px;
height: 16px;
color: var(--td-text-color-placeholder);
}
}
.catalog-stats {
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
margin-bottom: 14px;
// 待维护统计:与「草稿」状态同色(橙色提醒,2026-11 需求:不再用红色)
&__maintain {
margin-left: 6px;
&.is-alert {
color: var(--td-warning-color);
font-weight: 600;
}
}
}
.catalog-grid-wrap {
display: block;
min-height: 160px;
}
.catalog-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 16px;
}
.catalog-empty {
padding: 48px 0;
}
.course-card {
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
overflow: hidden;
cursor: pointer;
transition: box-shadow var(--app-motion-fast) ease, transform var(--app-motion-fast) ease;
&:hover {
transform: translateY(-2px);
box-shadow: var(--app-shadow-1, 0 6px 16px rgba(0, 0, 0, 0.08));
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
&__cover {
height: 118px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-md);
background: var(--td-bg-color-secondarycontainer);
svg {
width: 30px;
height: 30px;
}
&.is-online {
color: var(--td-brand-color);
background: linear-gradient(135deg, var(--td-brand-color-1, rgba(0, 82, 217, 0.08)), var(--td-bg-color-secondarycontainer));
}
&.is-offline {
color: var(--course-offline-blue, #0052d9);
background: linear-gradient(135deg, var(--course-offline-blue-bg, rgba(0, 82, 217, 0.08)), var(--td-bg-color-secondarycontainer));
}
}
&__body {
padding: 12px 14px 14px;
}
// 形式标签 + 「我的课程」角色标记(我主讲/我参加)同行展示
&__tags {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
&__name {
margin: 8px 0 4px;
font-size: var(--app-text-lg);
font-weight: 600;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__meta {
margin: 0 0 10px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__foot {
display: flex;
align-items: center;
gap: 10px;
}
&__bar {
flex: 1;
height: 5px;
border-radius: var(--app-radius-pill);
background: var(--td-bg-color-component);
overflow: hidden;
i {
display: block;
height: 100%;
border-radius: var(--app-radius-pill);
background: var(--td-brand-color);
transition: width 0.4s ease;
}
&.is-doing-bar i {
background: repeating-linear-gradient(45deg, var(--td-brand-color) 0 8px, var(--td-brand-color-2, rgba(0, 82, 217, 0.55)) 8px 16px);
background-size: 200% 100%;
animation: catalogBarFlow 1.6s linear infinite;
}
}
&__state {
flex-shrink: 0;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
&.is-good { color: var(--td-success-color); font-weight: 600; }
&.is-doing { color: var(--td-brand-color); }
&.is-warn { color: var(--td-warning-color); }
&.is-bad { color: var(--td-error-color); }
}
// 我任讲师课程的【维护课程】入口:小号文字按钮,点击不触发卡片跳转;
// 文案颜色与「草稿」状态一致(2026-11 需求:由品牌绿改为橙色)
&__maintain {
flex-shrink: 0;
border: 1px solid var(--td-warning-color);
background: transparent;
color: var(--td-warning-color);
font: inherit;
font-size: var(--app-text-sm);
line-height: 1;
padding: 4px 8px;
border-radius: var(--app-radius-sm);
cursor: pointer;
transition: all var(--app-motion-fast) ease;
&:hover {
background: var(--td-warning-color);
color: var(--td-text-color-anti);
}
&:focus-visible {
outline: 2px solid var(--td-warning-color);
outline-offset: 2px;
}
}
}
@keyframes catalogBarFlow {
from { background-position: 0 0; }
to { background-position: 32px 0; }
}
</style>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,323 @@
<template>
<div class="member-panel">
<!-- 员工档案(名册来自组织架构)+ 职称角色 -->
<div class="panel-box member-layout__members">
<div class="panel-box__header">
<span class="panel-box__title">员工档案</span>
<div class="member-panel__hint">
员工与部门在「<a class="member-panel__link" @click="goOrgCenter">组织架构</a>」中统一维护,此处仅配置职称角色
<t-button variant="outline" theme="primary" size="small" :loading="syncing" class="oa-sync-btn" @click="onPreviewSync">
从OA同步企微账号
</t-button>
</div>
</div>
<t-table :data="members" :columns="memberColumns" row-key="id" size="small" :loading="loading">
<template #user_name="{ row }">
<t-tooltip :content="memberName(row)" :disabled="!memberName(row)">
<span class="member-name">{{ memberName(row) || '-' }}</span>
</t-tooltip>
</template>
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
<template #wecom_userid="{ row }">
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
</template>
<template #roles="{ row }">
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
<t-button variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
</template>
</t-table>
</div>
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
<template #footer>
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
</template>
</t-dialog>
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
<template v-if="syncSummary">
<div class="sync-stats">
<span>本地员工 {{ syncSummary.local_candidates }}</span>
<span>OA 命中 {{ syncSummary.local_matched }}</span>
<span>已一致 {{ syncSummary.already_bound }}</span>
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
</div>
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
{{ cf.employee_no }} {{ cf.user_name || '' }}:
{{ conflictText(cf) }}
</div>
</div>
<div v-if="syncSummary.would_update" class="sync-section">
<div class="sync-section__title">将写入(最多展示 20 条)</div>
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
</div>
</div>
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
无需更新:绑定已一致或 OA 无匹配数据。
</div>
<div class="sync-footer">
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
theme="primary" :loading="syncing" @click="onApplySync">
确认写入
</t-button>
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
</div>
</template>
</t-dialog>
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
<t-select v-model="roleSelection" multiple style="width: 100%">
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
</t-select>
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onSaveRoles">保存</t-button>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import {
fetchRoleDict,
listMembers,
listPlatformUsers,
roleLabelOf,
updateMemberRoles,
updateMemberWecomUserid,
applyWecomUseridSync,
previewWecomUseridSync,
type PlatformUser,
type TrainingMember,
type TrainingRoleDef,
type WecomSyncConflict,
type WecomSyncSummary,
unwrap,
} from '@/api/training'
const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const members = ref<TrainingMember[]>([])
const platformUsers = ref<PlatformUser[]>([])
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
const roleDict = ref<TrainingRoleDef[]>([])
const rolesVisible = ref(false)
const activeMember = ref<TrainingMember | null>(null)
const roleSelection = ref<string[]>([])
// 企微账号绑定(培训提醒推送目标)
const wecomVisible = ref(false)
const activeWecomMember = ref<TrainingMember | null>(null)
const wecomInput = ref('')
const savingWecom = ref(false)
// OA 同步(工号 → 企微 userid,预览→写入两段式)
const syncVisible = ref(false)
const syncing = ref(false)
const syncSummary = ref<WecomSyncSummary | null>(null)
const conflictText = (cf: WecomSyncConflict) => {
switch (cf.reason) {
case 'duplicate_workcode_in_oa':
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
case 'bound_to_different_userid':
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
case 'userid_occupied':
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
default:
return cf.reason
}
}
const onPreviewSync = async () => {
syncing.value = true
try {
const res = await previewWecomUseridSync()
syncSummary.value = unwrap(res) ?? null
syncVisible.value = true
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
} finally {
syncing.value = false
}
}
const onApplySync = async () => {
syncing.value = true
try {
const res = await applyWecomUseridSync()
const summary = unwrap(res)
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
syncVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '写入失败')
} finally {
syncing.value = false
}
}
const memberColumns = [
{ colKey: 'employee_no', title: '工号', width: 100 },
{ colKey: 'user_name', title: '姓名' },
{ colKey: 'dept_name', title: '部门', width: 110 },
{ colKey: 'post', title: '岗位', width: 140 },
{ colKey: 'wecom_userid', title: '企微账号', width: 120 },
{ colKey: 'roles', title: '职称角色', width: 260 },
{ colKey: 'op', title: '操作', width: 170 },
]
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
// 跳转组织架构页(部门/员工档案的唯一维护入口)
const goOrgCenter = () => router.push('/platform/org-center')
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不再回退展示用户ID。
const userNameMap = computed(() => {
const m: Record<string, string> = {}
for (const u of platformUsers.value) m[u.id] = u.display_name?.trim() || u.username
return m
})
const memberName = (row: TrainingMember) => row.user_name || userNameMap.value[row.user_id] || ''
const loadAll = async () => {
loading.value = true
try {
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
const [m, u] = await Promise.all([
listMembers({ page_size: 500 }),
listPlatformUsers().catch(() => null),
])
members.value = unwrap(m)?.items || []
platformUsers.value = unwrap(u) || []
} finally {
loading.value = false
}
}
const openRoles = (row: TrainingMember) => {
activeMember.value = row
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
rolesVisible.value = true
}
const openWecom = (row: TrainingMember) => {
activeWecomMember.value = row
wecomInput.value = row.wecom_userid || ''
wecomVisible.value = true
}
const onSaveWecom = async () => {
if (!activeWecomMember.value) return
savingWecom.value = true
try {
await updateMemberWecomUserid(activeWecomMember.value.id, wecomInput.value.trim())
MessagePlugin.success('企微账号已更新')
wecomVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
savingWecom.value = false
}
}
const onSaveRoles = async () => {
if (!activeMember.value) return
saving.value = true
try {
await updateMemberRoles(activeMember.value.id, [...roleSelection.value, 'trainee'])
MessagePlugin.success('角色已更新')
rolesVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
saving.value = false
}
}
onMounted(() => {
loadAll()
fetchRoleDict().then((d) => {
roleDict.value = d
})
})
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.panel-box {
.training-panel-box();
}
.member-panel__hint {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.member-panel__link {
color: var(--td-brand-color);
cursor: pointer;
}
.role-tag { margin-right: 4px; }
.wecom-missing { color: var(--td-text-color-placeholder); }
.oa-sync-btn { margin-left: 12px; }
.sync-stats {
display: flex;
gap: 14px;
flex-wrap: wrap;
margin-bottom: 12px;
color: var(--td-text-color-secondary);
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
}
.sync-section {
margin-bottom: 12px;
max-height: 180px;
overflow: auto;
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
}
.sync-footer { display: flex; gap: 8px; justify-content: flex-end; }
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 姓名列:最多展示 2 行,超出省略(悬停 tooltip 看全名)
.member-name {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
word-break: break-all;
line-height: 1.4;
}
</style>
@@ -0,0 +1,996 @@
<template>
<div class="rule-panel">
<!-- 卡片1:职称角色 · 角色与权限(点选式维护,自定义角色勾选权限分配即生效) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">职称角色 · 角色与权限</span>
<t-button variant="outline" size="small" @click="openRoleDialog()">新增角色</t-button>
</div>
<t-table :data="roleRows" :columns="roleColumns" row-key="key" size="small" :loading="roleLoading">
<template #role="{ row }">
<span class="role-name">{{ row.label }}</span>
<t-tag v-if="row.system" theme="primary" variant="light" size="small" class="role-sys-tag">系统</t-tag>
</template>
<template #key="{ row }">
<code class="role-key">{{ row.key }}</code>
</template>
<template #inherits="{ row }">
<span v-if="!(row.inherits || []).length" class="perm-none">—</span>
<t-tag
v-for="p in row.inherits || []"
:key="p"
variant="light"
size="small"
class="perm-tag"
>{{ roleLabelOf(p, roleRows, true) }}</t-tag>
</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="openRoleDialog(row)">编辑</t-button>
<t-popconfirm
v-if="!row.system"
content="删除该角色?仍持有该角色的成员将回退为普通学员权限。"
theme="danger"
@confirm="onDeleteRole(row)"
>
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
</template>
</t-table>
<div class="form-hint">
系统角色不可删除,展示名与权限分配可改;「权限分配」= 继承所选权限组的全部接口与页面权限,勾选多个取并集。学员为全员默认角色,无需配置。
</div>
</div>
<!-- 卡片2:业务规则(全部点选式表单,不再手写 JSON) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">业务规则</span>
<t-button variant="outline" size="small" :loading="seeding" @click="onSeed">初始化默认配置</t-button>
</div>
<div class="panel-box__sub">点选即可修改,每项保存后立即生效;未保存的修改不生效。</div>
<div v-for="schema in RULE_SCHEMAS" :key="schema.key" class="rule-section">
<div class="rule-section__head">
<span class="rule-section__title">{{ schema.title }}</span>
<span class="rule-section__desc">{{ schema.desc }}</span>
<t-button
variant="outline"
size="small"
:disabled="!isDirty(schema.key)"
:loading="savingKey === schema.key"
@click="onSaveRule(schema.key)"
>保存</t-button>
</div>
<div class="rule-section__fields">
<div
v-for="field in schema.fields"
:key="field.key"
class="rule-field"
:class="{ 'rule-field--block': field.type === 'text' }"
>
<span class="rule-field__label">{{ field.label }}</span>
<t-input-number
v-if="field.type === 'number'"
v-model="ruleValues[schema.key][field.key]"
:min="field.min"
:max="field.max"
theme="normal"
size="small"
class="rule-field__input"
/>
<t-switch
v-else-if="field.type === 'switch'"
v-model="ruleValues[schema.key][field.key]"
/>
<!-- [2026-11 需求] 提醒推送文案等文本模板:整行多行文本,支持 {占位符} -->
<t-textarea
v-else
v-model="ruleValues[schema.key][field.key]"
:autosize="{ minRows: 2, maxRows: 4 }"
:placeholder="field.placeholder"
class="rule-field__textarea"
/>
<span v-if="field.unit" class="rule-field__unit">{{ field.unit }}</span>
<span v-if="field.vars" class="rule-field__vars">可用变量:{{ field.vars }}</span>
</div>
</div>
<div v-if="schema.key === 'lecturer_score_weight'" class="rule-sum" :class="{ 'rule-sum--warn': weightSum !== 100 }">
三项权重合计:{{ weightSum }}<template v-if="weightSum !== 100">(建议合计 100)</template>
</div>
</div>
</div>
<!-- 高级配置:未提供点选表单的规则键,保留 JSON 编辑兜底 -->
<div v-if="advancedRows.length" class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">高级配置</span>
<span class="panel-box__sub">以下配置项暂无点选表单,按 JSON 格式编辑</span>
</div>
<t-table :data="advancedRows" :columns="advancedColumns" row-key="rule_key" size="small">
<template #rule_key="{ row }"><code class="role-key">{{ row.rule_key }}</code></template>
<template #rule_value="{ row }">
<code class="rule-json">{{ stringify(row.rule_value) }}</code>
</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="openEdit(row)">编辑</t-button>
</template>
</t-table>
</div>
<!-- 卡片3:推送记录(逐人企微/站内投递明细;手动触发周一讲师提醒) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">推送记录</span>
<div class="push-toolbar">
<t-select v-model="pushScene" class="push-scene-select" size="small" clearable placeholder="全部场景">
<t-option v-for="opt in PUSH_SCENE_OPTIONS" :key="opt.value" :value="opt.value" :label="opt.label" />
</t-select>
<t-button variant="outline" size="small" :loading="pushLogsLoading" @click="loadPushLogs">刷新</t-button>
<t-popconfirm content="立即执行一轮周一讲师未完成提醒?同一周重复执行不会重复推送。" theme="primary" @confirm="onRunWeekly">
<t-button variant="outline" theme="primary" size="small" :loading="runningWeekly">立即推送讲师提醒</t-button>
</t-popconfirm>
</div>
</div>
<t-table :data="pushLogs" :columns="pushLogColumns" row-key="id" size="small" :loading="pushLogsLoading" max-height="360">
<template #created_at="{ row }">{{ fmtTime(row.created_at) }}</template>
<template #scene="{ row }"><code class="role-key">{{ row.scene }}</code></template>
<template #target="{ row }">
<span>{{ row.target_name || row.target_user_id }}</span>
<span v-if="row.employee_no" class="push-empno">({{ row.employee_no }})</span>
</template>
<template #push_status="{ row }">
<t-tag
:theme="row.push_status === 'sent' ? 'success' : row.push_status === 'dead' || row.push_status === '' ? 'default' : row.push_status === 'pending' || row.push_status === 'sending' ? 'warning' : 'danger'"
variant="light" size="small"
>{{ pushStatusLabel(row.push_status) }}</t-tag>
</template>
<template #push_error="{ row }">
<span class="push-error" :title="row.push_error">{{ row.push_error || '—' }}</span>
</template>
</t-table>
<div class="form-hint">
展示最近 {{ pushLogs.length }} 条;pending/sending=排队与投递中,sent=企微已送达,skipped=收件人未绑定企微等跳过,dead=重试耗尽,空=仅站内通知。
</div>
</div>
<!-- 卡片4:导入模板管理(上传自定义 Excel 模板替换内置默认) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">导入模板</span>
<span class="panel-box__sub">上传后,培训计划批量导入与题库 Excel 导入的下载入口即刻使用新模板</span>
</div>
<t-table :data="templates" :columns="templateColumns" row-key="template_key" size="small" :loading="templateLoading">
<template #file_name="{ row }">
<span>{{ row.file_name }}</span>
<t-tag v-if="row.source === 'custom'" theme="primary" variant="light" size="small" class="tpl-tag">自定义</t-tag>
<t-tag v-else theme="default" variant="light" size="small" class="tpl-tag">内置默认</t-tag>
</template>
<template #file_size="{ row }">{{ fmtSize(row.file_size) }}</template>
<template #updated_at="{ row }">{{ row.source === 'custom' ? fmtTime(row.updated_at) : '—' }}</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="onDownloadTemplate(row)">下载</t-button>
<t-button variant="text" theme="primary" size="small" @click="onPickUpload(row)">上传更新</t-button>
<t-popconfirm
v-if="row.source === 'custom'"
content="恢复为内置默认模板?"
theme="danger"
@confirm="onResetTemplate(row)"
>
<t-button variant="text" theme="danger" size="small">恢复默认</t-button>
</t-popconfirm>
</template>
</t-table>
<div class="form-hint">仅支持 .xls / .xlsx,不超过 10MB;上传后原有内置模板仍可通过「恢复默认」找回。</div>
<!-- 复用的隐藏文件选择器:记录待上传模板键 -->
<input
ref="uploadInput"
type="file"
accept=".xls,.xlsx"
class="tpl-upload-input"
@change="onUploadFile"
/>
</div>
<!-- 角色编辑弹窗 -->
<t-dialog
v-model:visible="roleDialogVisible"
:header="roleForm.mode === 'add' ? '新增职称角色' : `编辑职称角色 · ${roleForm.label || roleForm.key}`"
width="480"
>
<t-form label-width="88px">
<t-form-item label="角色标识">
<t-input
v-model="roleForm.key"
:disabled="roleForm.mode === 'edit'"
placeholder="小写字母开头,仅含小写字母/数字/下划线,如 trainer"
/>
</t-form-item>
<t-form-item label="显示名">
<t-input v-model="roleForm.label" placeholder="如:培训专员" />
</t-form-item>
<t-form-item label="短名">
<t-input v-model="roleForm.short" placeholder="成员列表标签展示,缺省同显示名" />
</t-form-item>
<t-form-item label="权限分配">
<t-select v-model="roleForm.inherits" multiple clearable placeholder="点选要赋予的权限组(可多选)">
<t-option
v-for="r in inheritOptions"
:key="r.key"
:value="r.key"
:label="`${r.label}权限组`"
/>
</t-select>
</t-form-item>
</t-form>
<div class="form-hint">
权限分配决定该角色能使用哪些功能:如勾选「课长权限组+讲师权限组」即可管理培训计划与维护课程(经理权限组已包含课长全部权限与审批决策)。保存后立即生效,无需重启。
</div>
<template #footer>
<t-button theme="primary" :loading="roleSaving" @click="onSaveRole">保存</t-button>
</template>
</t-dialog>
<!-- 高级配置 JSON 编辑弹窗 -->
<t-dialog v-model:visible="editVisible" :header="`编辑规则 · ${activeKey}`" width="560">
<t-textarea v-model="editText" :autosize="{ minRows: 10 }" />
<div class="form-hint">JSON 格式,保存后立即生效;历史数据不受影响。</div>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import {
ROLE_DICT_RULE_KEY,
deleteTrainingTemplate,
fetchRoleDict,
listRuleConfigs,
listTrainingPushLogs,
listTrainingTemplates,
roleLabelOf,
runWeeklyLecturerReminders,
saveRuleConfig,
seedRuleConfigs,
uploadTrainingTemplate,
type TrainingPushLog,
type TrainingRoleDef,
type TrainingRuleConfig,
type TrainingTemplateKey,
type TrainingTemplateMeta,
unwrap,
} from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime'
import { downloadTrainingTemplate } from '../trainingTemplates'
const loading = ref(false)
const saving = ref(false)
const editVisible = ref(false)
const editText = ref('')
const activeKey = ref('')
// ---------------------------------------------------------------------------
// 职称角色 · 角色与权限
// ---------------------------------------------------------------------------
const roleLoading = ref(false)
const roleRows = ref<TrainingRoleDef[]>([])
const roleColumns = [
{ colKey: 'role', title: '角色', width: 210 },
{ colKey: 'key', title: '标识', width: 110 },
{ colKey: 'inherits', title: '权限分配', minWidth: 200 },
{ colKey: 'op', title: '操作', width: 130 },
]
const loadRoles = async () => {
roleLoading.value = true
try {
roleRows.value = await fetchRoleDict()
} finally {
roleLoading.value = false
}
}
const roleDialogVisible = ref(false)
const roleSaving = ref(false)
const roleForm = ref<{ mode: 'add' | 'edit'; key: string; label: string; short: string; inherits: string[] }>({
mode: 'add',
key: '',
label: '',
short: '',
inherits: [],
})
// 权限组选项 = 系统角色(排除自身,自分配无意义且后端会拦截)
const inheritOptions = computed(() => roleRows.value.filter((r) => r.system && r.key !== roleForm.value.key))
const openRoleDialog = (row?: TrainingRoleDef) => {
roleForm.value = row
? { mode: 'edit', key: row.key, label: row.label, short: row.short || '', inherits: [...(row.inherits || [])] }
: { mode: 'add', key: '', label: '', short: '', inherits: [] }
roleDialogVisible.value = true
}
// 与后端 ParseRoleDict 同口径的前端校验(点选场景先提示,不依赖 400)
const ROLE_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/
const onSaveRole = async () => {
const f = roleForm.value
const key = f.key.trim()
const label = f.label.trim()
if (f.mode === 'add' && !ROLE_KEY_RE.test(key)) {
MessagePlugin.warning('角色标识需小写字母开头,仅含小写字母/数字/下划线')
return
}
if (f.mode === 'add' && roleRows.value.some((r) => r.key === key)) {
MessagePlugin.warning(`角色标识 ${key} 已存在`)
return
}
if (!label) {
MessagePlugin.warning('显示名不能为空')
return
}
if (f.inherits.includes(key)) {
MessagePlugin.warning('不能分配自身权限组')
return
}
// 经理 = 课长全部权限 + 审批决策:必须分配课长权限组(与后端硬约束同口径)
if (key === 'exec' && !f.inherits.includes('supervisor')) {
MessagePlugin.warning('经理权限组必须分配课长权限组(经理 = 课长全部权限 + 审批决策)')
return
}
const short = f.short.trim() || label
const next: TrainingRoleDef[] =
f.mode === 'add'
? [...roleRows.value, { key, label, short, system: false, inherits: [...f.inherits] }]
: roleRows.value.map((r) => (r.key === key ? { ...r, label, short, inherits: [...f.inherits] } : r))
roleSaving.value = true
try {
await saveRuleConfig(ROLE_DICT_RULE_KEY, { roles: next })
MessagePlugin.success('角色已保存并生效')
roleDialogVisible.value = false
roleRows.value = next
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
roleSaving.value = false
}
}
const onDeleteRole = async (row: TrainingRoleDef) => {
const next = roleRows.value.filter((r) => r.key !== row.key)
try {
await saveRuleConfig(ROLE_DICT_RULE_KEY, { roles: next })
MessagePlugin.success('角色已删除')
roleRows.value = next
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '删除失败')
}
}
// ---------------------------------------------------------------------------
// 业务规则(点选式表单;字段描述驱动,与后端 defaultRuleSeed 同源)
// ---------------------------------------------------------------------------
interface RuleFieldDesc {
key: string
label: string
type: 'number' | 'switch' | 'text'
min?: number
max?: number
unit?: string
/** text 字段的输入提示 */
placeholder?: string
/** text 字段(文案模板)支持的 {占位符} 列表提示 */
vars?: string
}
interface RuleSchemaDesc {
key: string
title: string
desc: string
fields: RuleFieldDesc[]
// serialize UI 表单值 → tr_rule_configs 落库值(默认原样 JSON);
// notify_remind_days(数组)/notify_push_enabled(bool) 等非对象契约用。
serialize?: (v: Record<string, any>) => any
// parse 落库值 → UI 表单值(缺省视为对象原样)。
parse?: (saved: any) => Record<string, any>
}
const RULE_SCHEMAS: RuleSchemaDesc[] = [
{
key: 'sign_policy',
title: '签到策略',
desc: '课堂签到的迟到判定与定位校验',
fields: [
{ key: 'late_after_min', label: '迟到阈值', type: 'number', min: 1, max: 120, unit: '分钟后算迟到' },
{ key: 'geo_radius_m', label: '定位有效半径', type: 'number', min: 50, max: 5000, unit: '米' },
{ key: 'require_geo', label: '强制定位校验', type: 'switch' },
],
},
{
key: 'lecturer_score_weight',
title: '讲师评分权重',
desc: '讲师综合分的三个构成维度权重',
fields: [
{ key: 'on_time', label: '按时开课', type: 'number', min: 0, max: 100 },
{ key: 'rating', label: '学员评分', type: 'number', min: 0, max: 100 },
{ key: 'qa', label: '互动答疑', type: 'number', min: 0, max: 100 },
],
},
{
key: 'point_rules',
title: '积分规则',
desc: '学员完成相应学习行为获得的积分',
fields: [
{ key: 'required', label: '完成必修课', type: 'number', min: 0, max: 1000 },
{ key: 'score_90', label: '考试 ≥90 分', type: 'number', min: 0, max: 1000 },
{ key: 'score_100', label: '考试 100 分', type: 'number', min: 0, max: 1000 },
{ key: 'pass', label: '考试普通及格', type: 'number', min: 0, max: 1000 },
{ key: 'elective', label: '完成选修课', type: 'number', min: 0, max: 1000 },
{ key: 'self_study', label: '自学线上课件', type: 'number', min: 0, max: 1000 },
],
},
{
// [2026-11 推送管理] 接线真实调度器契约:scheduler 读 notify_remind_days 数组
// (training_scheduler.go loadNotifyConfig);原 remind_policy(t3/t1/third_week/
// month_end)从未被后端读取,由本卡替换(third_week/month_end 无实现,随卡移除)。
key: 'notify_remind_days',
title: '开课提醒时点',
desc: '调度器按提前天数生成讲师授课提醒;学员开课通知由场次"通知方式"决定(立即或前一天),不受本项影响',
fields: [
{ key: 't3', label: '开课前 3 天提醒', type: 'switch' },
{ key: 't1', label: '开课前 1 天提醒', type: 'switch' },
],
serialize: (v) => [...(v.t3 ? [3] : []), ...(v.t1 ? [1] : [])],
// 配置行不存在时必须返回 {} 让 DEFAULT_RULE_VALUES 打底(true),不能显式 false。
parse: (saved) =>
saved === undefined || saved === null
? {}
: {
t3: Array.isArray(saved) && saved.includes(3),
t1: Array.isArray(saved) && saved.includes(1),
},
},
{
key: 'notify_push_enabled',
title: '企微推送总开关',
desc: '关闭后新产生的通知只保留站内流水,不再推送企业微信;已入队消息不受影响',
fields: [{ key: 'enabled', label: '启用企微推送', type: 'switch' }],
serialize: (v) => !!v.enabled,
parse: (saved) =>
saved === undefined || saved === null ? {} : { enabled: saved === true || saved?.enabled === true },
},
{
key: 'notify_weekly_lecturer',
title: '周一讲师未完成提醒',
desc: '每周一上午向当月仍有未结束场次的讲师推送汇总提醒(标题带第 N 周);讲师场次全部结束即自动停推',
fields: [
{ key: 'enabled', label: '启用周一提醒', type: 'switch' },
{ key: 'hour', label: '发送时刻', type: 'number', min: 0, max: 23, unit: '点(北京时间)' },
],
serialize: (v) => ({ enabled: !!v.enabled, hour: Number(v.hour) || 9 }),
parse: (saved) =>
saved === undefined || saved === null
? {}
: { enabled: saved?.enabled !== false, hour: Number(saved?.hour ?? 9) },
},
{
// [2026-11 需求] 提醒推送文案可编辑:各提醒场景的标题/内容模板,保存后新推送即刻生效;
// {占位符} 渲染时替换为实际值,清空保存即恢复内置默认文案(后端空值回落默认)。
key: 'notify_text_templates',
title: '提醒推送文案',
desc: '各提醒推送的标题与内容模板,支持 {占位符} 替换实际值;清空并保存即恢复内置默认文案,对保存后的新推送生效',
fields: [
{
key: 'student_notice_title',
label: '学员开课通知 · 标题',
type: 'text',
placeholder: '培训开课通知',
vars: '{course}(仅站内通知标题生效;企微消息自动追加「:课程名」)',
},
{
key: 'student_notice_content',
label: '学员开课通知 · 内容',
type: 'text',
vars: '{course} 课程名 / {time} 开课时间 / {place} 地点或线上说明 / {lecturer} 讲师(缺省「待定」)',
},
{
key: 'lecturer_open_title',
label: '讲师授课提醒 · 标题',
type: 'text',
placeholder: '授课提醒',
vars: '无需变量(自动追加「:课程名」)',
},
{ key: 'lecturer_open_footer', label: '讲师授课提醒 · 结尾', type: 'text' },
{
key: 'lecturer_maintain_title',
label: '课程维护提醒 · 标题',
type: 'text',
placeholder: '课程维护提醒',
vars: '无需变量(自动追加「:课程名」)',
},
{ key: 'lecturer_maintain_footer', label: '课程维护提醒 · 结尾', type: 'text' },
{ key: 'weekly_title', label: '周一讲师提醒 · 标题', type: 'text', vars: '{year} / {month} / {week}' },
{
key: 'weekly_content',
label: '周一讲师提醒 · 内容',
type: 'text',
vars: '{year} / {month} / {week} / {week_start} / {week_end} 本周起止(MM-DD) / {count} 未结束场次',
},
],
},
{
key: 'pass_line',
title: '岗位胜任达标线',
desc: '课程考试的默认及格分数线',
fields: [{ key: 'default', label: '默认及格线', type: 'number', min: 0, max: 100, unit: '分' }],
},
{
key: 'roll_policy',
title: '滚动规则',
desc: '连续未完成任务的升级提醒阈值',
fields: [{ key: 'escalate_after', label: '连续未完成', type: 'number', min: 1, max: 12, unit: '次后升级提醒' }],
},
]
// 默认值打底(与后端 defaultRuleSeed 一致):规则键尚未初始化时也能直接点选配置
const DEFAULT_RULE_VALUES: Record<string, Record<string, any>> = {
lecturer_score_weight: { on_time: 40, rating: 50, qa: 10 },
point_rules: { required: 10, score_90: 10, score_100: 20, pass: 5, elective: 5, self_study: 3 },
sign_policy: { late_after_min: 15, geo_radius_m: 300, require_geo: false },
pass_line: { default: 75 },
roll_policy: { escalate_after: 2 },
// [2026-11 推送管理] 企微推送卡默认值(与调度器缺省一致)
notify_remind_days: { t3: true, t1: true },
notify_push_enabled: { enabled: true },
notify_weekly_lecturer: { enabled: true, hour: 9 },
// [2026-11 需求] 提醒推送文案默认模板(与后端 defaultNotifyTextTemplates 逐字一致)
notify_text_templates: {
student_notice_title: '培训开课通知',
student_notice_content: '您被点名参加「{course}」培训:{time},{place},讲师:{lecturer}。请准时参加。',
lecturer_open_title: '授课提醒',
lecturer_open_footer: '请准时参加,详情见培训平台。',
lecturer_maintain_title: '课程维护提醒',
lecturer_maintain_footer:
'该课程尚未上传课件/学习材料,请尽快登录培训平台补齐,以免影响学员课前学习。',
weekly_title: '{year}年{month}月教育训练(第{week}周提醒)',
weekly_content:
'{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。',
},
}
const RULE_SCHEMA_KEYS = new Set(RULE_SCHEMAS.map((s) => s.key))
const ruleValues = ref<Record<string, Record<string, any>>>({})
const savedSnapshot = ref<Record<string, string>>({})
const savingKey = ref('')
const advancedRows = ref<TrainingRuleConfig[]>([])
const advancedColumns = [
{ colKey: 'rule_key', title: '规则', width: 220 },
{ colKey: 'rule_value', title: '配置值' },
{ colKey: 'op', title: '操作', width: 80 },
]
const stringify = (v: any) => JSON.stringify(v ?? {})
const applyConfigs = (configs: TrainingRuleConfig[]) => {
const values: Record<string, Record<string, any>> = {}
const snapshot: Record<string, string> = {}
for (const schema of RULE_SCHEMAS) {
const savedRaw = configs.find((c) => c.rule_key === schema.key)?.rule_value
// parse 转换落库契约(数组/bool)为 UI 表单形态;缺省视为对象。
const saved = schema.parse ? schema.parse(savedRaw) : savedRaw || {}
// 默认值打底 + 已保存值覆盖 + 保留配置中的其他键(保存时不丢字段)
const merged: Record<string, any> = { ...(DEFAULT_RULE_VALUES[schema.key] || {}) }
for (const k of Object.keys(saved)) merged[k] = saved[k]
values[schema.key] = merged
snapshot[schema.key] = JSON.stringify(merged)
}
ruleValues.value = values
savedSnapshot.value = snapshot
advancedRows.value = configs.filter(
(c) => !RULE_SCHEMA_KEYS.has(c.rule_key) && c.rule_key !== ROLE_DICT_RULE_KEY,
)
}
const loadAll = async () => {
loading.value = true
try {
const res = await listRuleConfigs()
applyConfigs(unwrap<TrainingRuleConfig[]>(res) || [])
} finally {
loading.value = false
}
}
// ---- 推送记录(2026-11 推学员/推讲师需求,逐人企微/站内投递明细) ----
const PUSH_SCENE_OPTIONS = [
{ value: 'session_notice_student', label: '学员开课通知' },
{ value: 'remind_monthly_lecturer', label: '周一讲师提醒' },
{ value: 'remind_lecturer_maintain', label: '课程维护提醒' },
]
const pushScene = ref('')
const pushLogs = ref<TrainingPushLog[]>([])
const pushLogsLoading = ref(false)
const runningWeekly = ref(false)
const pushLogColumns = [
{ colKey: 'created_at', title: '时间', width: 150 },
{ colKey: 'scene', title: '场景', width: 180 },
{ colKey: 'title', title: '标题', ellipsis: true },
{ colKey: 'target', title: '收件人', width: 150 },
{ colKey: 'push_status', title: '企微状态', width: 100 },
{ colKey: 'push_error', title: '失败原因', ellipsis: true },
]
const pushStatusLabel = (status: string) => {
if (!status) return '仅站内'
const map: Record<string, string> = {
pending: '排队中',
sending: '投递中',
sent: '已送达',
skipped: '已跳过',
dead: '已失败',
}
return map[status] || status
}
const loadPushLogs = async () => {
pushLogsLoading.value = true
try {
const res = await listTrainingPushLogs({ scenes: pushScene.value || undefined, limit: 200 })
pushLogs.value = unwrap<TrainingPushLog[]>(res) || []
} finally {
pushLogsLoading.value = false
}
}
const onRunWeekly = async () => {
runningWeekly.value = true
try {
await runWeeklyLecturerReminders()
MessagePlugin.success('已触发,讲师提醒将按轮次幂等入队并推送')
loadPushLogs()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '触发失败')
} finally {
runningWeekly.value = false
}
}
const isDirty = (key: string) => JSON.stringify(ruleValues.value[key]) !== savedSnapshot.value[key]
const weightSum = computed(() => {
const v = ruleValues.value.lecturer_score_weight || {}
return (Number(v.on_time) || 0) + (Number(v.rating) || 0) + (Number(v.qa) || 0)
})
// 数字字段被清空时回填默认值,避免保存出 null 破坏后端取值
const buildRulePayload = (schemaKey: string) => {
const schema = RULE_SCHEMAS.find((s) => s.key === schemaKey)
const out: Record<string, any> = { ...(ruleValues.value[schemaKey] || {}) }
for (const f of schema?.fields || []) {
if (out[f.key] === null || out[f.key] === undefined || out[f.key] === '') {
out[f.key] = DEFAULT_RULE_VALUES[schemaKey]?.[f.key] ?? 0
}
}
return out
}
const onSaveRule = async (schemaKey: string) => {
const schema = RULE_SCHEMAS.find((s) => s.key === schemaKey)
savingKey.value = schemaKey
try {
const uiValues = buildRulePayload(schemaKey)
// serialize:UI 表单值 → 落库契约(数组/bool 等,见 RuleSchemaDesc.serialize)。
const payload = schema?.serialize ? schema.serialize(uiValues) : uiValues
await saveRuleConfig(schemaKey, payload)
ruleValues.value = { ...ruleValues.value, [schemaKey]: uiValues }
savedSnapshot.value = { ...savedSnapshot.value, [schemaKey]: JSON.stringify(uiValues) }
MessagePlugin.success('规则已保存并生效')
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
savingKey.value = ''
}
}
// ---- 高级配置(JSON 兜底) ----
const openEdit = (row: TrainingRuleConfig) => {
activeKey.value = row.rule_key
editText.value = JSON.stringify(row.rule_value ?? {}, null, 2)
editVisible.value = true
}
const onSave = async () => {
let parsed: any
try {
parsed = JSON.parse(editText.value)
} catch {
MessagePlugin.warning('请输入合法的 JSON')
return
}
saving.value = true
try {
await saveRuleConfig(activeKey.value, parsed)
MessagePlugin.success('规则已保存并生效')
editVisible.value = false
loadAll()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '保存失败')
} finally {
saving.value = false
}
}
const seeding = ref(false)
const onSeed = async () => {
seeding.value = true
try {
const res = await seedRuleConfigs()
MessagePlugin.success(`已初始化 ${unwrap(res)?.seeded ?? 0} 条默认规则(已存在的键不覆盖)`)
loadAll()
loadRoles()
} catch {
MessagePlugin.error('初始化失败')
} finally {
seeding.value = false
}
}
// ---- 导入模板 ----
const templateLoading = ref(false)
const templates = ref<TrainingTemplateMeta[]>([])
const uploadInput = ref<HTMLInputElement | null>(null)
const uploadKey = ref<TrainingTemplateKey | null>(null)
const templateColumns = [
{ colKey: 'file_name', title: '模板' },
{ colKey: 'file_size', title: '大小', width: 90 },
{ colKey: 'updated_at', title: '上传时间', width: 160 },
{ colKey: 'op', title: '操作', width: 210 },
]
const fmtSize = (size: number) => (size >= 1024 ? `${(size / 1024).toFixed(1)} KB` : `${size} B`)
const fmtTime = (raw: string) => fmtBeijingTime(raw) || '—'
const loadTemplates = async () => {
templateLoading.value = true
try {
const res = await listTrainingTemplates()
templates.value = unwrap(res) || []
} catch {
templates.value = []
} finally {
templateLoading.value = false
}
}
const onDownloadTemplate = (row: TrainingTemplateMeta) =>
downloadTrainingTemplate(row.template_key, row.file_name)
// 每行「上传更新」复用同一个隐藏 input,先记录目标模板键
const onPickUpload = (row: TrainingTemplateMeta) => {
uploadKey.value = row.template_key
uploadInput.value?.click()
}
const onUploadFile = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
const key = uploadKey.value
if (!file || !key) return
try {
const fd = new FormData()
fd.append('file', file)
await uploadTrainingTemplate(key, fd)
MessagePlugin.success('模板已上传,各下载入口即刻生效')
loadTemplates()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '上传失败,仅支持 .xls/.xlsx 且不超过 10MB')
} finally {
uploadKey.value = null
}
}
const onResetTemplate = async (row: TrainingTemplateMeta) => {
try {
await deleteTrainingTemplate(row.template_key)
MessagePlugin.success('已恢复为内置默认模板')
loadTemplates()
} catch {
MessagePlugin.error('操作失败')
}
}
onMounted(() => {
loadAll()
loadRoles()
loadTemplates()
loadPushLogs()
})
// 场景筛选变化即重拉推送记录
watch(pushScene, () => loadPushLogs())
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.panel-box {
.training-panel-box();
& + .panel-box {
margin-top: 12px;
}
&__sub {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
}
.rule-json {
font-size: var(--app-text-sm);
word-break: break-all;
}
.tpl-tag {
margin-left: 6px;
}
// 复用的隐藏文件选择器
.tpl-upload-input {
display: none;
}
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// ---- 职称角色 ----
.role-name {
margin-right: 6px;
}
.role-sys-tag {
margin-left: 6px;
}
.role-key {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
word-break: break-all;
}
.perm-tag {
margin-right: 6px;
}
.perm-none {
color: var(--td-text-color-placeholder);
}
// ---- 业务规则点选式分区 ----
.rule-section {
padding: 12px 0;
& + .rule-section {
border-top: 1px solid var(--td-component-stroke);
}
&__head {
display: flex;
align-items: baseline;
gap: 10px;
.t-button {
margin-left: auto;
}
}
&__title {
font-weight: 600;
font-size: var(--app-text-base);
}
&__desc {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
&__fields {
margin-top: 10px;
display: flex;
flex-wrap: wrap;
gap: 10px 28px;
}
}
.rule-field {
display: inline-flex;
align-items: center;
gap: 8px;
&__label {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
white-space: nowrap;
}
&__input {
width: 130px;
}
&__unit {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
white-space: nowrap;
}
// 文案模板等长文本:整行块状布局(标签一行 + 多行输入 + 变量提示)
&--block {
display: flex;
flex-direction: column;
align-items: stretch;
width: 100%;
gap: 6px;
}
&__textarea {
width: 100%;
}
&__vars {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-xs);
}
}
.rule-sum {
margin-top: 8px;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
&--warn {
color: var(--td-warning-color);
}
}
/* 推送记录工具行与明细(2026-11 推送管理) */
.push-toolbar {
display: flex;
gap: 8px;
align-items: center;
}
.push-scene-select {
width: 180px;
}
.push-empno {
margin-left: 4px;
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
}
.push-error {
display: inline-block;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-error-color);
}
</style>
@@ -0,0 +1,613 @@
// training_notify.go 推送管理核心(2026-11 推学员/推讲师需求)。
//
// 三条链路,统一走 tr_notifications outbox(站内流水 + 企微 push_status 投递):
// 1. 学员开课通知 scene=session_notice_student,ref=场次 ID:
// immediate 场次在名单保存/课件上传后立即入队;day_before 场次由
// TrainingScheduler 在开课前 1 天推送(课件门控,上传后本文件补推钩子兜底);
// (tenant,target,scene,ref) 唯一索引幂等,一人一场最多一条。
// 2. 周一讲师未完成汇总提醒 scene=remind_monthly_lecturer,ref=YYYY-MM-Wn:
// TrainingScheduler 每周 N(北京时间 09:00,规则可配)扫描当月仍有未结束
// 场次的讲师;场次全部结束即停推(收件人集合自然过滤);手动触发共用本文件
// 的轮次键,幂等防重。
// 3. 推送记录:管理端逐人明细(tr_notifications push_status + 员工姓名映射)。
//
// 手动推送(NotifySessionStudents/RunWeeklyLecturerReminders)只写通知行,
// 不直接调企微:运行中的 TrainingScheduler dispatchPending 消费 pending 行。
package service
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
)
// 周一讲师汇总提醒的规则键(ruleKeyNotifyWeeklyLecturer* 定义在
// training_scheduler.go,同包共享);defaultWeeklyRemindHour 与需求"每周一 09:00"
// 一致(北京时间)。pushLogDefaultLimit 推送记录默认拉取条数。
const (
defaultWeeklyRemindHour = 9
pushLogDefaultLimit = 200
)
// beijingZone 需求口径统一 Asia/Shanghai(周次/发送时点不随服务器时区漂移)。
var beijingZone = time.FixedZone("Asia/Shanghai", 8*3600)
// ---------------------------------------------------------------------------
// 规则读取
// ---------------------------------------------------------------------------
// loadPushEnabled reads notify_push_enabled (默认 true):false 时新入队的通知行
// 只保留站内流水,push_status 置空不进企微外箱。
func (s *trainingService) loadPushEnabled(ctx context.Context, tenantID uint64) bool {
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
if err != nil {
return true
}
for _, rule := range rules {
if rule.RuleKey == ruleKeyNotifyPushEnabled {
var enabled bool
if json.Unmarshal(rule.RuleValue, &enabled) == nil {
return enabled
}
}
}
return true
}
// weeklyLecturerRule reads the Monday lecturer reminder policy from
// tr_rule_configs:组合键 notify_weekly_lecturer({"enabled","hour"},配置中心卡)
// 优先;独立键 notify_weekly_lecturer_enabled / notify_weekly_remind_hour 兼容;
// 缺省开、09:00(北京时间)。
func (s *trainingService) weeklyLecturerRule(ctx context.Context, tenantID uint64) (bool, int) {
enabled, hour := true, defaultWeeklyRemindHour
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
if err != nil {
return enabled, hour
}
for _, rule := range rules {
switch rule.RuleKey {
case ruleKeyNotifyWeeklyLecturer:
var combined struct {
Enabled *bool `json:"enabled"`
Hour *int `json:"hour"`
}
if json.Unmarshal(rule.RuleValue, &combined) == nil {
if combined.Enabled != nil {
enabled = *combined.Enabled
}
if combined.Hour != nil && *combined.Hour >= 0 && *combined.Hour <= 23 {
hour = *combined.Hour
}
}
case ruleKeyNotifyWeeklyLecturerEnabled:
var v bool
if json.Unmarshal(rule.RuleValue, &v) == nil {
enabled = v
}
case ruleKeyNotifyWeeklyRemindHour:
var v int
if json.Unmarshal(rule.RuleValue, &v) == nil && v >= 0 && v <= 23 {
hour = v
}
}
}
return enabled, hour
}
// ---------------------------------------------------------------------------
// 推送文案模板([2026-11 需求] 配置中心「提醒推送文案」可编辑,空字段回落默认)
// ---------------------------------------------------------------------------
// notifyTextTemplates 各提醒场景的文案模板,占位符形如 {course}/{time};
// 只做占位符替换不引入富模板语法,避免配置中心编辑出语法错误。
type notifyTextTemplates struct {
// 学员开课通知(scene=session_notice_student):站内标题与内容
StudentNoticeTitle string `json:"student_notice_title"`
StudentNoticeContent string `json:"student_notice_content"`
// 讲师授课提醒(T-N):通知标题前缀与企微 markdown 结尾文案
//(标题自动追加「:课程名」,无需占位符;结尾文案同时用于 T-1 学员企微消息)
LecturerOpenTitle string `json:"lecturer_open_title"`
LecturerOpenFooter string `json:"lecturer_open_footer"`
// 课程维护提醒(临近开课仍缺课件):通知标题前缀与结尾文案
LecturerMaintainTitle string `json:"lecturer_maintain_title"`
LecturerMaintainFooter string `json:"lecturer_maintain_footer"`
// 周一讲师未完成汇总提醒:标题与内容
WeeklyTitle string `json:"weekly_title"`
WeeklyContent string `json:"weekly_content"`
}
// 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。
const (
defaultStudentNoticeTitle = "培训开课通知"
defaultStudentNoticeContent = "您被点名参加「{course}」培训:{time},{place},讲师:{lecturer}。请准时参加。"
defaultLecturerOpenTitle = "授课提醒"
defaultLecturerOpenFooter = "请准时参加,详情见培训平台。"
defaultLecturerMaintainTitle = "课程维护提醒"
defaultLecturerMaintainFooter = "该课程尚未上传课件/学习材料,请尽快登录培训平台补齐,以免影响学员课前学习。"
defaultWeeklyTitle = "{year}年{month}月教育训练(第{week}周提醒)"
defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
)
func defaultNotifyTextTemplates() notifyTextTemplates {
return notifyTextTemplates{
StudentNoticeTitle: defaultStudentNoticeTitle,
StudentNoticeContent: defaultStudentNoticeContent,
LecturerOpenTitle: defaultLecturerOpenTitle,
LecturerOpenFooter: defaultLecturerOpenFooter,
LecturerMaintainTitle: defaultLecturerMaintainTitle,
LecturerMaintainFooter: defaultLecturerMaintainFooter,
WeeklyTitle: defaultWeeklyTitle,
WeeklyContent: defaultWeeklyContent,
}
}
// parseNotifyTextTemplates 解析租户配置(空字段回落默认,解析失败整体用默认);
// trainingService(经 repo)与 TrainingScheduler(直查 db)共用。
func parseNotifyTextTemplates(raw []byte) notifyTextTemplates {
t := defaultNotifyTextTemplates()
var saved notifyTextTemplates
if len(raw) == 0 || json.Unmarshal(raw, &saved) != nil {
return t
}
fill := func(dst *string, v string) {
if strings.TrimSpace(v) != "" {
*dst = v
}
}
fill(&t.StudentNoticeTitle, saved.StudentNoticeTitle)
fill(&t.StudentNoticeContent, saved.StudentNoticeContent)
fill(&t.LecturerOpenTitle, saved.LecturerOpenTitle)
fill(&t.LecturerOpenFooter, saved.LecturerOpenFooter)
fill(&t.LecturerMaintainTitle, saved.LecturerMaintainTitle)
fill(&t.LecturerMaintainFooter, saved.LecturerMaintainFooter)
fill(&t.WeeklyTitle, saved.WeeklyTitle)
fill(&t.WeeklyContent, saved.WeeklyContent)
return t
}
// loadNotifyTextTemplates 读取配置中心 notify_text_templates(缺行 = 全默认)。
func (s *trainingService) loadNotifyTextTemplates(ctx context.Context, tenantID uint64) notifyTextTemplates {
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
if err != nil {
return defaultNotifyTextTemplates()
}
for _, rule := range rules {
if rule.RuleKey == ruleKeyNotifyTextTemplates {
return parseNotifyTextTemplates(rule.RuleValue)
}
}
return defaultNotifyTextTemplates()
}
// renderNotifyTemplate {name} 占位符替换;模板为空返回空串,未提供的占位符原样保留。
func renderNotifyTemplate(tpl string, vars map[string]string) string {
if tpl == "" {
return ""
}
pairs := make([]string, 0, len(vars)*2)
for k, v := range vars {
pairs = append(pairs, "{"+k+"}", v)
}
return strings.NewReplacer(pairs...).Replace(tpl)
}
// ---------------------------------------------------------------------------
// 学员开课通知(immediate 立即推 / day_before 调度器推,共用 scene 幂等)
// ---------------------------------------------------------------------------
// sessionMaterialsReady 课件门控:课程下已上传至少一份课件(需求:老师上传课件
// 及相关信息后方可通知学员)。
func (s *trainingService) sessionMaterialsReady(ctx context.Context, tenantID uint64, courseID string) bool {
if courseID == "" {
return false
}
materials, err := s.repo.ListMaterials(ctx, tenantID, courseID)
return err == nil && len(materials) > 0
}
// sessionNoticeTargets resolves the roster's platform user IDs for a session
// (tr_enrollments.member_id → org_employees.user_id,去重去空)。
func (s *trainingService) sessionNoticeTargets(ctx context.Context, tenantID uint64, sessionID string) ([]string, error) {
enrolls, err := s.repo.ListEnrollments(ctx, tenantID, sessionID)
if err != nil {
return nil, err
}
seen := map[string]bool{}
out := make([]string, 0, len(enrolls))
for _, e := range enrolls {
member, err := s.repo.GetMember(ctx, tenantID, e.MemberID)
if err != nil || member == nil || member.UserID == "" || seen[member.UserID] {
continue
}
seen[member.UserID] = true
out = append(out, member.UserID)
}
return out, nil
}
// sessionNoticeText 组装学员开课通知文案(时间/地点或线上链接/讲师)。
// [2026-11 需求] 文案模板在配置中心「提醒推送文案」可编辑;占位符:
// {course} 课程名 / {time} 开课时间 / {place} 地点或线上说明 / {lecturer} 讲师(缺省渲染「待定」)。
func (s *trainingService) sessionNoticeText(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession) (string, string) {
courseName := sessionCourseTitle(ctx, s, tenantID, session)
place := session.Location
if session.OnlineURL != "" {
place = "线上会议(链接见课程页)"
}
lecturerName := "待定"
if lecturer, err := s.repo.GetMember(ctx, tenantID, session.LecturerID); err == nil && lecturer != nil && lecturer.UserName != "" {
lecturerName = lecturer.UserName
}
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
title := renderNotifyTemplate(tpl.StudentNoticeTitle, map[string]string{"course": courseName})
content := renderNotifyTemplate(tpl.StudentNoticeContent, map[string]string{
"course": courseName,
"time": sessionTimeText(session),
"place": place,
"lecturer": lecturerName,
})
return title, content
}
// enqueueSessionNotices 对名单内尚未收到开课通知的学员入队(站内+企微外箱),
// 返回本轮新入队条数。已通知过滤 + 唯一索引兜底双重幂等。
func (s *trainingService) enqueueSessionNotices(
ctx context.Context, tenantID uint64, session *types.TrainingCourseSession, targets []string, push bool,
) (int, error) {
if len(targets) == 0 {
return 0, nil
}
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeCourseSession, session.ID)
if err != nil {
return 0, err
}
notified := map[string]bool{}
for _, row := range existing {
if row.Scene == types.SceneSessionNoticeStudent {
notified[row.TargetUserID] = true
}
}
title, content := s.sessionNoticeText(ctx, tenantID, session)
now := time.Now()
rows := make([]*types.TrainingNotification, 0, len(targets))
for _, uid := range targets {
if uid == "" || notified[uid] {
continue
}
notified[uid] = true
status := ""
if push {
status = pushStatusPending
}
rows = append(rows, &types.TrainingNotification{
ID: trainingNewID(),
TenantID: tenantID,
TargetUserID: uid,
Channel: "inapp",
Scene: types.SceneSessionNoticeStudent,
Title: title,
Content: content,
RefType: types.RefTypeCourseSession,
RefID: session.ID,
SentAt: now,
PushStatus: status,
})
}
if len(rows) == 0 {
return 0, nil
}
if err := s.repo.CreateNotifications(ctx, rows); err != nil {
return 0, err
}
logger.Infof(ctx, "[TrainingNotify] session %s: enqueued %d student notices (push=%v)",
session.ID, len(rows), push)
return len(rows), nil
}
// dispatchSessionNoticesIfNeeded 名单/课件就绪后的统一入口:
// - immediate:课件就绪即推(课件未就绪静默跳过,上传课件后由 afterMaterialUploaded 补推);
// - day_before:不立即推(调度器 T-1 负责),但若已进入 24h 窗口(扫描时点已过)
// 且课件就绪,降级立即补推,避免学员什么都收不到。
func (s *trainingService) dispatchSessionNoticesIfNeeded(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession) {
if session == nil || session.Status == types.TrainingSessionCancelled {
return
}
if !s.sessionMaterialsReady(ctx, tenantID, session.CourseID) {
return
}
if session.NotifyMode == types.TrainingNotifyModeDayBefore {
start := time.Now()
if session.StartAt != nil {
start = *session.StartAt
}
if time.Until(start) > 24*time.Hour {
return // 还没到 T-1 窗口,交给调度器
}
}
targets, err := s.sessionNoticeTargets(ctx, tenantID, session.ID)
if err != nil {
logger.Warnf(ctx, "[TrainingNotify] session %s targets: %v", session.ID, err)
return
}
if _, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID)); err != nil {
logger.Warnf(ctx, "[TrainingNotify] session %s enqueue: %v", session.ID, err)
}
}
// AfterEnrollmentsChanged 名单保存(SetEnrollments)后的通知钩子。
func (s *trainingService) AfterEnrollmentsChanged(ctx context.Context, tenantID uint64, sessionID string) {
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
if err != nil || session == nil {
return
}
s.dispatchSessionNoticesIfNeeded(ctx, tenantID, session)
}
// AfterMaterialUploaded 课件上传后的补推钩子:扫描该课程近未来(当月+下月)的
// 活跃场次,immediate 场次补推未通知学员;day_before 场次若已进入 T-1 窗口同样
// 补推(此时调度器时点已过或即将到点,统一由本钩子兜底,幂等保证不重发)。
func (s *trainingService) AfterMaterialUploaded(ctx context.Context, tenantID uint64, courseID string) {
now := time.Now()
for _, ym := range [][2]int{{now.Year(), int(now.Month())}, {now.Add(30 * 24 * time.Hour).Year(), int(now.Add(30 * 24 * time.Hour).Month())}} {
sessions, err := s.repo.ListMonthActiveSessions(ctx, tenantID, ym[0], ym[1])
if err != nil {
logger.Warnf(ctx, "[TrainingNotify] material hook month %d-%d: %v", ym[0], ym[1], err)
continue
}
for _, session := range sessions {
if session.CourseID != courseID {
continue
}
s.dispatchSessionNoticesIfNeeded(ctx, tenantID, session)
}
}
}
// NotifySessionStudents 手动"立即推送学员"(配置中心/场次操作):课件门控+
// 幂等,返回 (新入队, 已通知跳过) 计数。
func (s *trainingService) NotifySessionStudents(ctx context.Context, tenantID uint64, sessionID, operatorID string) (int, int, error) {
_ = operatorID
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
if err != nil || session == nil {
return 0, 0, errors.NewNotFoundError("课程场次不存在")
}
if session.Status == types.TrainingSessionCancelled {
return 0, 0, errors.NewBadRequestError("场次已取消,无法通知")
}
if !s.sessionMaterialsReady(ctx, tenantID, session.CourseID) {
return 0, 0, errors.NewBadRequestError("课件尚未上传,请先在课程管理上传课件")
}
targets, err := s.sessionNoticeTargets(ctx, tenantID, sessionID)
if err != nil {
return 0, 0, err
}
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeCourseSession, sessionID)
if err != nil {
return 0, 0, err
}
notified := map[string]bool{}
for _, row := range existing {
if row.Scene == types.SceneSessionNoticeStudent {
notified[row.TargetUserID] = true
}
}
skipped := 0
for _, uid := range targets {
if notified[uid] {
skipped++
}
}
queued, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID))
return queued, skipped, err
}
// ---------------------------------------------------------------------------
// 周一讲师未完成汇总提醒
// ---------------------------------------------------------------------------
// beijingNow returns now in Asia/Shanghai (需求时区口径)。
func beijingNow(now time.Time) time.Time {
return now.In(beijingZone)
}
// weekOfMonth counts how many Mondays have arrived in the month (含当天,
// 按北京时间):2026-10-19 是 10 月第三个周一 → 第 3 周。
func weekOfMonth(local time.Time) int {
first := time.Date(local.Year(), local.Month(), 1, 0, 0, 0, 0, local.Location())
offset := (int(first.Weekday()) + 6) % 7 // 距月初最近的周一已过天数(周一=0)
firstMonday := first.AddDate(0, 0, offset)
if local.Before(firstMonday) {
return 1
}
return int(local.Sub(firstMonday).Hours()/24)/7 + 1
}
// monthWeekRefID builds the monthly reminder round key, e.g. "2026-11-W3".
func monthWeekRefID(local time.Time) string {
return fmt.Sprintf("%04d-%02d-W%d", local.Year(), int(local.Month()), weekOfMonth(local))
}
// pendingMonthlyLecturers 汇总"当月仍有未结束场次"的讲师:
// key=lecturer member id,value=未结束(结束时间晚于 now)场次数。
// 场次全部结束的讲师不在集合里 → 天然实现"完成即停推";无场次的讲师也不推。
func (s *trainingService) pendingMonthlyLecturers(
ctx context.Context, tenantID uint64, year, month int, now time.Time,
) (map[string]int, error) {
sessions, err := s.repo.ListMonthActiveSessions(ctx, tenantID, year, month)
if err != nil {
return nil, err
}
pending := map[string]int{}
for _, sess := range sessions {
if sess.LecturerID == "" {
continue
}
end := now.Add(time.Nanosecond)
if sess.EndAt != nil {
end = *sess.EndAt
} else if sess.StartAt != nil {
end = *sess.StartAt
}
if !end.After(now) {
continue // 已结束,不算未完成
}
pending[sess.LecturerID]++
}
return pending, nil
}
// enqueueWeeklyLecturerReminders 生成一轮周一讲师汇总提醒(不判断发送窗口,
// 由调度器/手动触发各自把关),返回新入队条数。轮次键 ref=YYYY-MM-Wn 幂等,
// 同一周内重复触发(定时+手动)不重发。
func (s *trainingService) enqueueWeeklyLecturerReminders(
ctx context.Context, tenantID uint64, now time.Time, push bool,
) (int, error) {
local := beijingNow(now)
refID := monthWeekRefID(local)
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeMonth, refID)
if err != nil {
return 0, err
}
notified := map[string]bool{}
for _, row := range existing {
if row.Scene == types.SceneRemindMonthlyLecturer {
notified[row.TargetUserID] = true
}
}
pending, err := s.pendingMonthlyLecturers(ctx, tenantID, local.Year(), int(local.Month()), now)
if err != nil {
return 0, err
}
// [2026-11 需求] 文案模板在配置中心「提醒推送文案」可编辑;占位符:
// {year} 年 / {month} 月 / {week} 当月第几周 / {week_start} {week_end} 本周起止(MM-DD) / {count} 未结束场次数
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
baseVars := map[string]string{
"year": strconv.Itoa(local.Year()),
"month": strconv.Itoa(int(local.Month())),
"week": strconv.Itoa(weekOfMonth(local)),
"week_start": "",
"week_end": "",
}
weekStart := local.AddDate(0, 0, -int(local.Weekday()+6)%7)
weekEnd := weekStart.AddDate(0, 0, 6)
baseVars["week_start"] = weekStart.Format("01-02")
baseVars["week_end"] = weekEnd.Format("01-02")
title := renderNotifyTemplate(tpl.WeeklyTitle, baseVars)
rows := make([]*types.TrainingNotification, 0, len(pending))
for lecturerMemberID, count := range pending {
member, err := s.repo.GetMember(ctx, tenantID, lecturerMemberID)
if err != nil || member == nil || member.UserID == "" {
continue
}
if notified[member.UserID] {
continue
}
notified[member.UserID] = true
vars := make(map[string]string, len(baseVars)+1)
for k, v := range baseVars {
vars[k] = v
}
vars["count"] = strconv.Itoa(count)
content := renderNotifyTemplate(tpl.WeeklyContent, vars)
status := ""
if push {
status = pushStatusPending
}
rows = append(rows, &types.TrainingNotification{
ID: trainingNewID(),
TenantID: tenantID,
TargetUserID: member.UserID,
Channel: "inapp",
Scene: types.SceneRemindMonthlyLecturer,
Title: title,
Content: content,
RefType: types.RefTypeMonth,
RefID: refID,
SentAt: now,
PushStatus: status,
})
}
if len(rows) == 0 {
return 0, nil
}
if err := s.repo.CreateNotifications(ctx, rows); err != nil {
return 0, err
}
logger.Infof(ctx, "[TrainingNotify] weekly lecturer reminder %s: enqueued %d", refID, len(rows))
return len(rows), nil
}
// weeklyLecturerDueNow 判断当前北京时间是否处于周一提醒发送窗口
// (周一且小时等于配置值;调度器 5 分钟 tick,窗口命中一小时)。
func (s *trainingService) weeklyLecturerDueNow(ctx context.Context, tenantID uint64, now time.Time) bool {
enabled, hour := s.weeklyLecturerRule(ctx, tenantID)
if !enabled {
return false
}
local := beijingNow(now)
return local.Weekday() == time.Monday && local.Hour() == hour
}
// RunWeeklyLecturerReminders 手动触发一轮讲师汇总提醒(不看发送窗口,轮次键
// 幂等,同周重复点击不重发),返回新入队条数。
func (s *trainingService) RunWeeklyLecturerReminders(ctx context.Context, tenantID uint64, operatorID string) (int, error) {
_ = operatorID
return s.enqueueWeeklyLecturerReminders(ctx, tenantID, time.Now(), s.loadPushEnabled(ctx, tenantID))
}
// ---------------------------------------------------------------------------
// 推送记录(管理台逐人明细)
// ---------------------------------------------------------------------------
// ListPushLogs 管理端逐人推送明细:tr_notifications 按场景/引用过滤后映射
// 收件人姓名与工号(org_employees 联 users 展示名)。
func (s *trainingService) ListPushLogs(
ctx context.Context, tenantID uint64, scenes []string, refType string, limit int,
) ([]*types.TrainingPushLog, error) {
if limit <= 0 {
limit = pushLogDefaultLimit
}
rows, err := s.repo.ListPushLogs(ctx, tenantID, scenes, refType, limit)
if err != nil {
return nil, err
}
userIDs := make([]string, 0, len(rows))
for _, row := range rows {
userIDs = append(userIDs, row.TargetUserID)
}
members, _ := s.repo.ListMembersByUserIDs(ctx, tenantID, userIDs)
byUser := map[string]*types.TrainingMember{}
for _, m := range members {
byUser[m.UserID] = m
}
out := make([]*types.TrainingPushLog, 0, len(rows))
for _, row := range rows {
item := &types.TrainingPushLog{
ID: row.ID,
Scene: row.Scene,
Title: row.Title,
RefType: row.RefType,
RefID: row.RefID,
TargetUserID: row.TargetUserID,
PushStatus: row.PushStatus,
PushAttempts: row.PushAttempts,
PushedAt: row.PushedAt,
PushError: row.PushError,
SentAt: row.SentAt,
CreatedAt: row.CreatedAt,
}
if m := byUser[row.TargetUserID]; m != nil {
item.TargetName = m.UserName
item.EmployeeNo = m.EmployeeNo
}
out = append(out, item)
}
return out, nil
}
@@ -0,0 +1,36 @@
// training_notify_test.go 推送文案模板(配置中心「提醒推送文案」)的解析与渲染。
package service
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestParseNotifyTextTemplatesFallsBackToDefaults(t *testing.T) {
// 缺行/损坏 JSON → 整体内置默认
require.Equal(t, defaultNotifyTextTemplates(), parseNotifyTextTemplates(nil))
require.Equal(t, defaultNotifyTextTemplates(), parseNotifyTextTemplates([]byte("not json")))
// 自定义字段生效,空字段回落默认(配置中心"清空即恢复默认")
raw, err := json.Marshal(map[string]any{
"student_notice_title": "自定义开课标题",
"student_notice_content": "",
})
require.NoError(t, err)
got := parseNotifyTextTemplates(raw)
require.Equal(t, "自定义开课标题", got.StudentNoticeTitle)
require.Equal(t, defaultStudentNoticeContent, got.StudentNoticeContent)
require.Equal(t, defaultWeeklyTitle, got.WeeklyTitle)
}
func TestRenderNotifyTemplate(t *testing.T) {
require.Equal(t, "", renderNotifyTemplate("", map[string]string{"course": "x"}))
require.Equal(t,
"您被点名参加「安全培训」培训:11月18日 09:00,大会议室。请准时参加。",
renderNotifyTemplate("您被点名参加「{course}」培训:{time},{place}。请准时参加。",
map[string]string{"course": "安全培训", "time": "11月18日 09:00", "place": "大会议室"}))
// 未提供变量的占位符原样保留(不做删改,便于发现漏配)
require.Equal(t, "{a}-x", renderNotifyTemplate("{a}-{b}", map[string]string{"b": "x"}))
}
@@ -0,0 +1,257 @@
package service
import (
"context"
"encoding/json"
"fmt"
"sort"
"time"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
)
// ---------------------------------------------------------------------------
// 运营闭环补齐:代签到 / 学员取卷 / 代交卷 / 讲师结算 / 规则种子 / 平台用户
// ---------------------------------------------------------------------------
// CheckinFor 讲师/课长/人事代扫码/现场补录:以目标成员身份签到,proxy 标记留痕。
func (s *trainingService) CheckinFor(ctx context.Context, tenantID uint64, operatorUserID, token, targetMemberID string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) {
if targetMemberID == "" {
return nil, errors.NewBadRequestError("缺少代签成员")
}
target, err := s.repo.GetMember(ctx, tenantID, targetMemberID)
if err != nil {
return nil, errors.NewNotFoundError("成员不存在")
}
if target.UserID == operatorUserID {
return s.Checkin(ctx, tenantID, operatorUserID, token, lat, lng, channel)
}
// 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。
record, err := s.Checkin(ctx, tenantID, target.UserID, token, lat, lng, "proxy")
if err != nil {
return nil, err
}
// proxy 标记追加留痕(异常复核列表可见)。
flags := append(trainingJSONStrings(string(record.AbnormalFlags)), "proxy")
record.AbnormalFlags = trainingJSONFromSlice(flags)
if err := s.repo.ReviewSignRecord(ctx, record); err != nil {
return nil, err
}
return record, nil
}
// GetPaperForExam 学员答题视图:题目剥离答案与解析;课长/讲师/人事可见完整数据。
func (s *trainingService) GetPaperForExam(ctx context.Context, tenantID uint64, userID, paperID string) (*types.TrainingPaper, []*types.TrainingQuestion, error) {
paper, err := s.repo.GetPaper(ctx, tenantID, paperID)
if err != nil {
return nil, nil, errors.NewNotFoundError("试卷不存在")
}
member, memberErr := s.repo.GetMemberByUserID(ctx, tenantID, userID)
isStaff := false
if memberErr == nil && member != nil {
// 角色按字典权限分配展开后判定(自定义角色继承 hr/lecturer/supervisor 即视为运营人员)。
for _, r := range s.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList()) {
if r == types.TrainingRoleHR || r == types.TrainingRoleLecturer || r == types.TrainingRoleSupervisor {
isStaff = true
break
}
}
}
ids := trainingJSONStrings(string(paper.QuestionIDs))
questions, err := s.repo.ListQuestionsByIDs(ctx, tenantID, ids)
if err != nil {
return nil, nil, err
}
// 按组卷时的题序返回。
order := map[string]int{}
for i, id := range ids {
order[id] = i
}
sort.Slice(questions, func(i, j int) bool { return order[questions[i].ID] < order[questions[j].ID] })
// 展示分值用组卷时按满分 100 自动划分的试卷级分值(旧试卷回退题目自身分值)。
if paperScores := paperQuestionScores(paper); paperScores != nil {
for _, q := range questions {
if v, ok := paperScores[q.ID]; ok {
q.Score = v
}
}
}
if !isStaff {
for _, q := range questions {
q.Answer = ""
q.Analysis = ""
}
}
return paper, questions, nil
}
// SubmitExamFor 监考代交卷:课长/讲师/人事为线下答题的学员录入答卷。
func (s *trainingService) SubmitExamFor(ctx context.Context, tenantID uint64, operatorUserID, targetMemberID, paperID string, answers map[string]string) (*types.TrainingExamRecord, error) {
if targetMemberID == "" {
return nil, errors.NewBadRequestError("缺少交卷成员")
}
target, err := s.repo.GetMember(ctx, tenantID, targetMemberID)
if err != nil {
return nil, errors.NewNotFoundError("成员不存在")
}
paper, err := s.repo.GetPaper(ctx, tenantID, paperID)
if err != nil {
return nil, errors.NewNotFoundError("试卷不存在")
}
if target.UserID == operatorUserID {
return s.SubmitExam(ctx, tenantID, operatorUserID, paperID, answers)
}
// 走同一判分逻辑,以目标成员身份落卷。
return s.submitExamAs(ctx, tenantID, target, paper, answers)
}
// SettleLecturerScores 结算某月讲师综合分:
// 按时开课40%(场次完结率) + 学员评分50%(均值/5) + 互动答疑10%(已回复占比)。
func (s *trainingService) SettleLecturerScores(ctx context.Context, tenantID uint64, year, month int, operatorID string) ([]*types.TrainingLecturerScore, error) {
if month < 1 || month > 12 {
return nil, errors.NewBadRequestError("月份不合法")
}
weights := trainingJSONMap(s.ruleBytes(ctx, tenantID, types.RuleKeyLecturerScoreWeight))
wOnTime := trainingJSONFloat(weights, "on_time", 40)
wRating := trainingJSONFloat(weights, "rating", 50)
wQA := trainingJSONFloat(weights, "qa", 10)
stats, err := s.repo.LecturerMonthStats(ctx, tenantID, year, month)
if err != nil {
return nil, err
}
results := make([]*types.TrainingLecturerScore, 0, len(stats))
for _, st := range stats {
onTime := 0.0
if st.SessionsTotal > 0 {
onTime = float64(st.SessionsFinished) / float64(st.SessionsTotal)
}
avgRating, _ := s.repo.AvgRatingByLecturer(ctx, tenantID, st.LecturerID, year)
rating := avgRating / 5.0
pendings, _ := s.repo.PendingFeedbacks(ctx, tenantID, st.LecturerID)
allFeedbacks, _ := s.repo.ListFeedbacksByLecturer(ctx, tenantID, st.LecturerID, year)
qAnswered := 0.0
if len(allFeedbacks) > 0 {
qAnswered = float64(len(allFeedbacks)-len(pendings)) / float64(len(allFeedbacks))
}
total := onTime*wOnTime + rating*wRating + qAnswered*wQA
score := &types.TrainingLecturerScore{
ID: trainingNewID(), TenantID: tenantID, LecturerID: st.LecturerID,
Year: year, Month: month,
OnTimeScore: mathRound1(onTime * wOnTime),
RatingScore: mathRound1(rating * wRating),
QAScore: mathRound1(qAnswered * wQA),
Total: mathRound1(total),
}
if err := s.repo.UpsertLecturerScore(ctx, score); err != nil {
continue
}
results = append(results, score)
}
// 排名。
sort.SliceStable(results, func(i, j int) bool { return results[i].Total > results[j].Total })
for i, r := range results {
r.RankNo = i + 1
_ = s.repo.UpsertLecturerScore(ctx, r)
}
logger.Infof(ctx, "[Training] lecturer scores settled, tenant=%d %d-%02d lecturers=%d operator=%s",
tenantID, year, month, len(results), operatorID)
return results, nil
}
// defaultRuleSeed 一期默认规则(与落地方案 §11 的建议默认值一致)。
// [2026-11 推送管理] 追加企微推送三键,与 training_scheduler.loadNotifyConfig /
// training_notify.weeklyLecturerRule 的读取键对齐(缺行时后端有同值兜底,种子只为
// 配置中心"初始化默认配置"与高级配置可见性)。
func defaultRuleSeed() map[string]string {
roleDictRaw, _ := json.Marshal(map[string]any{"roles": types.DefaultRoleDict()})
// [2026-11 需求] 提醒推送文案默认模板(配置中心「提醒推送文案」卡)
notifyTextRaw, _ := json.Marshal(defaultNotifyTextTemplates())
return map[string]string{
types.RuleKeyLecturerScoreWeight: `{"on_time":40,"rating":50,"qa":10}`,
types.RuleKeyPointRules: `{"required":10,"score_90":10,"score_100":20,"pass":5,"elective":5,"self_study":3}`,
types.RuleKeyRemindPolicy: `{"t3":true,"t1":true,"third_week":true,"month_end":true}`,
types.RuleKeySignPolicy: `{"late_after_min":15,"geo_radius_m":300,"require_geo":false}`,
types.RuleKeyPassLine: `{"default":75}`,
types.RuleKeyRollPolicy: `{"escalate_after":2}`,
types.RuleKeyRoleDict: string(roleDictRaw),
ruleKeyNotifyRemindDays: `[3,1]`,
ruleKeyNotifyPushEnabled: `true`,
ruleKeyNotifyWeeklyLecturer: `{"enabled":true,"hour":9}`,
ruleKeyNotifyTextTemplates: string(notifyTextRaw),
}
}
// SeedRuleConfigs 初始化默认规则;已存在的键不覆盖(人事确认后再改)。
func (s *trainingService) SeedRuleConfigs(ctx context.Context, tenantID uint64, operatorID string) ([]*types.TrainingRuleConfig, error) {
seeded := []*types.TrainingRuleConfig{}
for key, raw := range defaultRuleSeed() {
if _, err := s.repo.GetRuleConfig(ctx, tenantID, key); err == nil {
continue
}
cfg := &types.TrainingRuleConfig{
ID: trainingNewID(), TenantID: tenantID,
RuleKey: key, RuleValue: types.JSON([]byte(raw)), UpdatedBy: operatorID,
}
if err := s.repo.UpsertRuleConfig(ctx, cfg); err != nil {
continue
}
seeded = append(seeded, cfg)
}
logger.Infof(ctx, "[Training] rule configs seeded, tenant=%d count=%d operator=%s", tenantID, len(seeded), operatorID)
return seeded, nil
}
// publishOnlineLearningTasks 线上课发布后按部门范围生成学习任务
// (必修推送全员/部门批量指派,默认 7 天期限,可配 learning_policy.default_days)。
func (s *trainingService) publishOnlineLearningTasks(ctx context.Context, tenantID uint64, course *types.TrainingCourse, operatorID string) {
members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining,
&types.OrgListQuery{Page: 1, PageSize: 1000})
if err != nil {
logger.Errorf(ctx, "[Training] learning tasks: list members failed: %v", err)
return
}
// 注意:DeptIDs 是 jsonb,"[]" 的字节长度大于 0,必须按解析后的元素判断范围。
scopeDepts := trainingJSONStrings(string(course.DeptIDs))
deadlineDays := int(s.ruleFloat(ctx, tenantID, "learning_policy", "default_days", 7))
deadline := time.Now().AddDate(0, 0, deadlineDays)
created, failed := 0, 0
for _, m := range members {
if m.Status != "active" {
continue
}
if len(scopeDepts) > 0 {
inScope := false
for _, d := range scopeDepts {
if d == m.DeptID {
inScope = true
break
}
}
if !inScope {
continue
}
}
task := &types.TrainingLearningTask{
ID: trainingNewID(), TenantID: tenantID,
CourseID: course.ID, MemberID: m.ID,
Deadline: &deadline,
RemindRule: "every_3_days",
Status: types.TrainingLearningPending,
}
if err := s.repo.UpsertLearningTask(ctx, task); err != nil {
failed++
continue
}
created++
_ = s.Notify(ctx, tenantID, m.UserID, "learning_task",
"线上学习任务", fmt.Sprintf("课程《%s》已发布,请在 %d 天内完成学习。", course.Name, deadlineDays),
"course", course.ID)
}
logger.Infof(ctx, "[Training] online learning tasks created, tenant=%d course=%s count=%d failed=%d operator=%s",
tenantID, course.ID, created, failed, operatorID)
}
@@ -0,0 +1,760 @@
// TrainingScheduler pushes scheduled training reminders to WeCom.
//
// It runs two deterministic (no-LLM) steps on a ticker, mirroring the
// AutomationService tick loop:
//
// 1. generateReminders — scans tr_course_sessions inside the horizon and
// writes tr_notifications rows for T-N day session reminders (students
// via tr_enrollments, lecturer via lecturer_id) and for the
// "maintain your course" lecturer reminder when the course has no
// materials. Idempotency is enforced by the partial unique index
// idx_tr_notifications_dedup (tenant_id, target_user_id, scene, ref_id).
// 2. dispatchPending — the WeCom outbox consumer: claims pending rows with
// FOR UPDATE SKIP LOCKED (multi-instance safe), resolves the tenant's
// webhook-mode WeCom IM channel credentials plus each user's
// org_employees.wecom_userid, sends markdown via /cgi-bin/message/send
// and records the result.
//
// Credentials are reused from the tenant's IM integration: a wecom channel
// in webhook (self-built app) mode. websocket-mode smart-bot credentials
// cannot call message/send and are ignored.
//
// The WeCom client construction is injected (WecomPushBackend, wired to
// internal/im/wecompush.Backend by the container) so this file never
// imports internal/im: internal/im's in-package tests import this package,
// and a service → im edge creates an import cycle in the im test binary.
package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"academy/internal/application/repository"
"academy/internal/logger"
"academy/internal/runtime"
"academy/internal/types"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// tr_notification push_status values (see migration 000144).
const (
pushStatusPending = "pending"
pushStatusSending = "sending"
pushStatusSent = "sent"
pushStatusSkipped = "skipped"
pushStatusDead = "dead"
)
// Tenant-configurable rule keys in tr_rule_configs (rule_value is the bare
// JSON value: [3,1], 7, true).
const (
ruleKeyNotifyRemindDays = "notify_remind_days"
ruleKeyNotifyLecturerMaintainDay = "notify_lecturer_maintain_days"
ruleKeyNotifyPushEnabled = "notify_push_enabled"
// ruleKeyNotifyWeeklyLecturer 组合键(配置中心一张卡):{"enabled":bool,"hour":int},
// 与下面的独立键双读兼容(组合键优先)。
ruleKeyNotifyWeeklyLecturer = "notify_weekly_lecturer"
ruleKeyNotifyWeeklyLecturerEnabled = "notify_weekly_lecturer_enabled"
ruleKeyNotifyWeeklyRemindHour = "notify_weekly_remind_hour"
// ruleKeyNotifyTextTemplates [2026-11 需求] 提醒推送文案模板(配置中心可编辑,
// 空字段回落 training_notify.go 的内置默认文案)。
ruleKeyNotifyTextTemplates = "notify_text_templates"
)
// sendingReclaimAfter bounds how long a claimed row may stay 'sending'
// before it is considered abandoned (instance crashed mid-dispatch) and put
// back to pending.
const sendingReclaimAfter = 10 * time.Minute
// WecomPushSender sends one markdown message to the listed WeCom userids.
// Satisfied by *wecom.ProactiveClient; an interface so tests inject fakes.
type WecomPushSender interface {
SendMarkdown(ctx context.Context, userIDs []string, content string) error
}
// WecomPushBackend resolves per-tenant push clients and platform-user →
// WeCom-userid bindings. Implemented by internal/im/wecompush (which owns
// the internal/im dependency the service layer must avoid).
type WecomPushBackend interface {
ClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (WecomPushSender, error)
TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error)
}
// SchedulerConfig holds scheduler tuning; zero fields keep defaults.
type TrainingSchedulerConfig struct {
// Tick is the scan interval.
Tick time.Duration
// RemindDaysBefore lists T-N days (relative to session start) that
// generate a reminder, e.g. [3,1].
RemindDaysBefore []int
// LecturerMaintainDays is T-N days for the lecturer maintain reminder.
LecturerMaintainDays int
// ScanHorizonDays limits how far ahead sessions are scanned.
ScanHorizonDays int
// DispatchBatch caps claimed rows per tick.
DispatchBatch int
// MaxPushAttempts caps retries before a row is marked dead.
MaxPushAttempts int
}
// DefaultTrainingSchedulerConfig returns the production defaults
// (T-3/T-1 reminders, maintain reminder at T-7).
func DefaultTrainingSchedulerConfig() *TrainingSchedulerConfig {
return &TrainingSchedulerConfig{
Tick: 5 * time.Minute,
RemindDaysBefore: []int{3, 1},
LecturerMaintainDays: 7,
ScanHorizonDays: 30,
DispatchBatch: 100,
MaxPushAttempts: 3,
}
}
// TrainingScheduler is the deterministic reminder engine for the training
// module. All state lives in tr_notifications (outbox), so any instance can
// run it; claiming is guarded by SKIP LOCKED.
type TrainingScheduler struct {
db *gorm.DB
cfg *TrainingSchedulerConfig
// backend resolves push clients and userid bindings; overridable in tests.
backend WecomPushBackend
now func() time.Time
stopCh chan struct{}
stopOne sync.Once
done chan struct{}
}
// NewTrainingScheduler constructs the scheduler (dig-injected). The backend
// comes from the container (wecompush.Backend).
func NewTrainingScheduler(db *gorm.DB, backend WecomPushBackend) *TrainingScheduler {
return &TrainingScheduler{
db: db,
cfg: DefaultTrainingSchedulerConfig(),
backend: backend,
now: time.Now,
stopCh: make(chan struct{}),
done: make(chan struct{}),
}
}
// Start launches the scan loop; it returns immediately.
func (s *TrainingScheduler) Start(ctx context.Context) {
go func() {
defer close(s.done)
ticker := time.NewTicker(s.cfg.Tick)
defer ticker.Stop()
for {
s.tick(ctx)
select {
case <-ctx.Done():
return
case <-s.stopCh:
return
case <-ticker.C:
}
}
}()
}
// StopWithin stops the loop and waits up to timeout for the current tick.
func (s *TrainingScheduler) StopWithin(timeout time.Duration) {
if s == nil {
return
}
s.stopOne.Do(func() { close(s.stopCh) })
if !runtime.WaitFor(s.done, timeout) {
logger.Warnf(context.Background(),
"[TrainingScheduler] tick still running after %s; continuing shutdown", timeout)
}
}
// tick runs one scan; a panic in one step must not kill the loop.
func (s *TrainingScheduler) tick(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
logger.Errorf(ctx, "[TrainingScheduler] tick panic: %v", r)
}
}()
s.reclaimStaleSending(ctx)
if err := s.generateReminders(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] generate reminders: %v", err)
}
if err := s.generateWeeklyLecturerReminders(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] weekly lecturer reminders: %v", err)
}
if err := s.dispatchPending(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] dispatch pending: %v", err)
}
}
// reclaimStaleSending puts rows stuck in 'sending' (crashed instance) back
// to pending so they are retried.
func (s *TrainingScheduler) reclaimStaleSending(ctx context.Context) {
err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
Where("push_status = ? AND updated_at < ?", pushStatusSending, s.now().Add(-sendingReclaimAfter)).
Updates(map[string]interface{}{
"push_status": pushStatusPending,
"updated_at": time.Now(),
}).Error
if err != nil {
logger.Warnf(ctx, "[TrainingScheduler] reclaim stale sending: %v", err)
}
}
// ---------------------------------------------------------------------------
// Step 1: generate reminders
// ---------------------------------------------------------------------------
// tenantNotifyConfig is the per-tenant reminder policy with defaults filled
// from the scheduler config and optional tr_rule_configs overrides.
type tenantNotifyConfig struct {
remindDays []int
lecturerMaintainIn int
pushEnabled bool
// texts 提醒推送文案模板([2026-11 需求] 配置中心「提醒推送文案」可编辑)
texts notifyTextTemplates
}
func (s *TrainingScheduler) generateReminders(ctx context.Context) error {
now := s.now()
horizon := now.Add(time.Duration(s.cfg.ScanHorizonDays) * 24 * time.Hour)
var sessions []types.TrainingCourseSession
if err := s.db.WithContext(ctx).
Where("deleted_at IS NULL AND status = ? AND start_at IS NOT NULL AND start_at > ? AND start_at <= ?",
types.TrainingSessionScheduled, now, horizon).
Find(&sessions).Error; err != nil {
return fmt.Errorf("scan sessions: %w", err)
}
if len(sessions) == 0 {
return nil
}
// Group sessions by tenant so rule configs load once per tenant.
byTenant := map[uint64][]types.TrainingCourseSession{}
for _, sess := range sessions {
byTenant[sess.TenantID] = append(byTenant[sess.TenantID], sess)
}
for tenantID, tenantSessions := range byTenant {
cfg, err := s.loadNotifyConfig(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "[TrainingScheduler] tenant %d rule config: %v", tenantID, err)
cfg = s.defaultNotifyConfig()
}
if err := s.generateForTenant(ctx, tenantID, tenantSessions, cfg, now); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] tenant %d generate: %v", tenantID, err)
}
}
return nil
}
func (s *TrainingScheduler) defaultNotifyConfig() tenantNotifyConfig {
days := append([]int(nil), s.cfg.RemindDaysBefore...)
return tenantNotifyConfig{
remindDays: days,
lecturerMaintainIn: s.cfg.LecturerMaintainDays,
pushEnabled: true,
texts: defaultNotifyTextTemplates(),
}
}
// loadNotifyConfig reads tenant overrides from tr_rule_configs; unknown or
// invalid values fall back to the scheduler defaults.
func (s *TrainingScheduler) loadNotifyConfig(ctx context.Context, tenantID uint64) (tenantNotifyConfig, error) {
cfg := s.defaultNotifyConfig()
var rules []types.TrainingRuleConfig
err := s.db.WithContext(ctx).
Where("tenant_id = ? AND rule_key IN ?", tenantID,
[]string{ruleKeyNotifyRemindDays, ruleKeyNotifyLecturerMaintainDay, ruleKeyNotifyPushEnabled, ruleKeyNotifyTextTemplates}).
Find(&rules).Error
if err != nil {
return cfg, err
}
for _, rule := range rules {
switch rule.RuleKey {
case ruleKeyNotifyRemindDays:
var days []int
if json.Unmarshal(rule.RuleValue, &days) == nil && len(days) > 0 {
valid := days[:0]
for _, d := range days {
if d > 0 && d <= s.cfg.ScanHorizonDays {
valid = append(valid, d)
}
}
if len(valid) > 0 {
cfg.remindDays = valid
}
}
case ruleKeyNotifyLecturerMaintainDay:
var days int
if json.Unmarshal(rule.RuleValue, &days) == nil && days > 0 && days <= s.cfg.ScanHorizonDays {
cfg.lecturerMaintainIn = days
}
case ruleKeyNotifyPushEnabled:
var enabled bool
if json.Unmarshal(rule.RuleValue, &enabled) == nil {
cfg.pushEnabled = enabled
}
case ruleKeyNotifyTextTemplates:
// [2026-11 需求] 提醒推送文案模板(空字段回落内置默认)
cfg.texts = parseNotifyTextTemplates(rule.RuleValue)
}
}
return cfg, nil
}
// generateForTenant writes due reminder rows for one tenant's sessions.
// Dedup pre-check avoids re-inserting; the partial unique index is the
// ultimate guard (ON CONFLICT DO NOTHING tolerates concurrent generation).
func (s *TrainingScheduler) generateForTenant(
ctx context.Context,
tenantID uint64,
sessions []types.TrainingCourseSession,
cfg tenantNotifyConfig,
now time.Time,
) error {
// Batch-load courses for titles.
courseIDs := make([]string, 0, len(sessions))
for _, sess := range sessions {
courseIDs = append(courseIDs, sess.CourseID)
}
courses, err := s.loadCourses(ctx, tenantID, courseIDs)
if err != nil {
return err
}
for _, sess := range sessions {
if sess.StartAt == nil {
continue
}
start := *sess.StartAt
course := courses[sess.CourseID]
// 1) T-N day reminders. [2026-11 推学员] 学员侧开课通知收敛到
// session_notice_student 单通道:immediate 场次由名单保存/课件上传钩子
// 立即入队(training_notify.go),调度器不再发学员 remind_tN 重复打扰;
// day_before 场次在 T-1 且课件就绪时在此入队(课件缺失跳过,上传课件后
// 补推钩子兜底)。讲师 remind_tN_lecturer 授课提醒保持不变。
for _, d := range cfg.remindDays {
if now.Before(start.Add(-time.Duration(d) * 24 * time.Hour)) {
continue
}
if sess.LecturerID != "" {
rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID,
types.TrainingRemindScene(d, true),
remindTitle(cfg.texts.LecturerOpenTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
sess.ID, cfg.pushEnabled, now)}
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
return err
}
}
if sess.NotifyMode != types.TrainingNotifyModeDayBefore || d != 1 {
continue
}
hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID)
if err != nil {
return err
}
if !hasMaterial {
continue
}
targets, err := s.sessionTargets(ctx, tenantID, sess)
if err != nil {
return err
}
rows := make([]*types.TrainingNotification, 0, len(targets))
for _, uid := range targets {
rows = append(rows, s.newReminderRow(tenantID, uid,
types.SceneSessionNoticeStudent,
remindTitle(cfg.texts.StudentNoticeTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
sess.ID, cfg.pushEnabled, now))
}
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
return err
}
}
// 2) Lecturer maintain reminder: inside the window and no materials.
if sess.LecturerID == "" {
continue
}
if now.Before(start.Add(-time.Duration(cfg.lecturerMaintainIn) * 24 * time.Hour)) {
continue
}
hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID)
if err != nil {
return err
}
if hasMaterial {
continue
}
rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID,
types.SceneRemindLecturerMaintain,
remindTitle(cfg.texts.LecturerMaintainTitle, course), remindContent(course, &sess, true, cfg.texts.LecturerMaintainFooter),
sess.ID, cfg.pushEnabled, now)}
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
return err
}
}
return nil
}
// sessionTargets resolves the student target user IDs (tr_enrollments →
// org_employees.user_id) for a session.
func (s *TrainingScheduler) sessionTargets(ctx context.Context, tenantID uint64, sess types.TrainingCourseSession) ([]string, error) {
var enrolls []types.TrainingEnrollment
if err := s.db.WithContext(ctx).
Where("tenant_id = ? AND session_id = ? AND deleted_at IS NULL", tenantID, sess.ID).
Find(&enrolls).Error; err != nil {
return nil, fmt.Errorf("list enrollments: %w", err)
}
if len(enrolls) == 0 {
return nil, nil
}
memberIDs := make([]string, 0, len(enrolls))
for _, e := range enrolls {
memberIDs = append(memberIDs, e.MemberID)
}
var members []types.OrgEmployee
if err := s.db.WithContext(ctx).
Where("tenant_id = ? AND id IN ?", tenantID, memberIDs).
Find(&members).Error; err != nil {
return nil, fmt.Errorf("load members: %w", err)
}
seen := map[string]bool{}
out := make([]string, 0, len(members))
for _, m := range members {
if m.UserID == "" || seen[m.UserID] {
continue
}
seen[m.UserID] = true
out = append(out, m.UserID)
}
return out, nil
}
func (s *TrainingScheduler) loadCourses(ctx context.Context, tenantID uint64, courseIDs []string) (map[string]types.TrainingCourse, error) {
out := map[string]types.TrainingCourse{}
if len(courseIDs) == 0 {
return out, nil
}
var courses []types.TrainingCourse
if err := s.db.WithContext(ctx).
Where("tenant_id = ? AND id IN ?", tenantID, courseIDs).
Find(&courses).Error; err != nil {
return nil, fmt.Errorf("load courses: %w", err)
}
for _, c := range courses {
out[c.ID] = c
}
return out, nil
}
func (s *TrainingScheduler) courseHasMaterial(ctx context.Context, tenantID uint64, courseID string) (bool, error) {
var count int64
err := s.db.WithContext(ctx).Model(&types.TrainingMaterial{}).
Where("tenant_id = ? AND course_id = ? AND deleted_at IS NULL", tenantID, courseID).
Limit(1).Count(&count).Error
return count > 0, err
}
// newReminderRow builds one tr_notifications row: always visible in the
// inapp inbox; push_status='pending' enqueues the WeCom outbox delivery.
func (s *TrainingScheduler) newReminderRow(
tenantID uint64, targetUserID, scene, title, content, sessionID string, push bool, now time.Time,
) *types.TrainingNotification {
status := ""
if push {
status = pushStatusPending
}
return &types.TrainingNotification{
ID: trainingNewID(),
TenantID: tenantID,
TargetUserID: targetUserID,
Channel: "inapp",
Scene: scene,
Title: title,
Content: content,
RefType: types.RefTypeCourseSession,
RefID: sessionID,
SentAt: now,
PushStatus: status,
}
}
// insertNotifications pre-checks duplicates for this (ref_id, targets) set
// and batch-inserts the rest; ON CONFLICT DO NOTHING is the race fallback.
func (s *TrainingScheduler) insertNotifications(ctx context.Context, tenantID uint64, sessionID string, rows []*types.TrainingNotification) error {
if len(rows) == 0 {
return nil
}
var existing []struct {
TargetUserID string
Scene string
}
if err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
Select("target_user_id, scene").
Where("tenant_id = ? AND ref_type = ? AND ref_id = ? AND deleted_at IS NULL",
tenantID, types.RefTypeCourseSession, sessionID).
Scan(&existing).Error; err != nil {
return fmt.Errorf("check existing notifications: %w", err)
}
seen := make(map[string]bool, len(existing))
for _, e := range existing {
seen[e.TargetUserID+"\x00"+e.Scene] = true
}
fresh := rows[:0]
for _, row := range rows {
if seen[row.TargetUserID+"\x00"+row.Scene] {
continue
}
seen[row.TargetUserID+"\x00"+row.Scene] = true
fresh = append(fresh, row)
}
if len(fresh) == 0 {
return nil
}
if err := s.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(&fresh).Error; err != nil {
return fmt.Errorf("insert notifications: %w", err)
}
logger.Infof(ctx, "[TrainingScheduler] tenant %d session %s: generated %d reminders",
tenantID, sessionID, len(fresh))
return nil
}
// ---------------------------------------------------------------------------
// Step 1.5: weekly lecturer monthly reminder (周一讲师未完成汇总)
// ---------------------------------------------------------------------------
// generateWeeklyLecturerReminders 每周一(北京时间,notify_weekly_remind_hour
// 规则可配,默认 09:00;notify_weekly_lecturer_enabled 可整体关闭)生成一轮
// "当月未完成讲师"汇总提醒:收件人 = 当月仍有未结束(结束时间晚于当前)场次
// 的讲师,场次全部结束即不在集合 → 天然"完成即停推"。轮次键 ref=YYYY-MM-Wn
// (按当月周一计数),同周内定时与手动触发共用幂等不重发。
// 租户集合取自当月活跃场次(无场次的租户没有未完成讲师,跳过)。
func (s *TrainingScheduler) generateWeeklyLecturerReminders(ctx context.Context) error {
now := s.now()
local := beijingNow(now)
if local.Weekday() != time.Monday {
return nil
}
var sessions []types.TrainingCourseSession
if err := s.db.WithContext(ctx).
Where("deleted_at IS NULL AND status IN ? AND year = ? AND month = ?",
[]string{types.TrainingSessionScheduled, types.TrainingSessionOngoing},
local.Year(), int(local.Month())).
Find(&sessions).Error; err != nil {
return fmt.Errorf("scan month sessions: %w", err)
}
if len(sessions) == 0 {
return nil
}
svc := &trainingService{repo: repository.NewTrainingRepository(s.db)}
tenants := map[uint64]bool{}
for _, sess := range sessions {
tenants[sess.TenantID] = true
}
for tenantID := range tenants {
// weeklyLecturerDueNow:开关 + 周一 + 配置小时(北京时间)统一判断
if !svc.weeklyLecturerDueNow(ctx, tenantID, now) {
continue
}
if _, err := svc.enqueueWeeklyLecturerReminders(ctx, tenantID, now, svc.loadPushEnabled(ctx, tenantID)); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] tenant %d weekly lecturer reminder: %v", tenantID, err)
}
}
return nil
}
// ---------------------------------------------------------------------------
// Step 2: dispatch the WeCom outbox
// ---------------------------------------------------------------------------
// claimedNotification mirrors the columns returned by the claim statement.
type claimedNotification struct {
ID string
TenantID uint64
TargetUserID string
Scene string
Title string
Content string
PushAttempts int
}
func (s *TrainingScheduler) dispatchPending(ctx context.Context) error {
var claimed []*claimedNotification
err := s.db.WithContext(ctx).Raw(`
UPDATE tr_notifications AS t
SET push_status = ?, updated_at = CURRENT_TIMESTAMP
FROM (
SELECT id FROM tr_notifications
WHERE push_status = ? AND deleted_at IS NULL
ORDER BY created_at, id
LIMIT ?
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`,
pushStatusSending, pushStatusPending, s.cfg.DispatchBatch).
Scan(&claimed).Error
if err != nil {
return fmt.Errorf("claim pending notifications: %w", err)
}
if len(claimed) == 0 {
return nil
}
byTenant := map[uint64][]*claimedNotification{}
for _, row := range claimed {
byTenant[row.TenantID] = append(byTenant[row.TenantID], row)
}
for tenantID, rows := range byTenant {
s.dispatchTenant(ctx, tenantID, rows)
}
return nil
}
func (s *TrainingScheduler) dispatchTenant(ctx context.Context, tenantID uint64, rows []*claimedNotification) {
client, clientErr := s.backend.ClientForTenant(ctx, s.db, tenantID)
if clientErr != nil {
logger.Warnf(ctx, "[TrainingScheduler] tenant %d wecom client: %v", tenantID, clientErr)
}
targets := make([]string, 0, len(rows))
for _, row := range rows {
targets = append(targets, row.TargetUserID)
}
mapping := map[string]string{}
if client != nil {
var err error
mapping, err = s.backend.TenantWecomUserIDs(ctx, s.db, tenantID, targets)
if err != nil {
logger.Warnf(ctx, "[TrainingScheduler] tenant %d wecom userid lookup: %v", tenantID, err)
mapping = map[string]string{}
}
}
for _, row := range rows {
switch {
case clientErr != nil:
s.finishPush(ctx, row, pushStatusSkipped, nil, clientErr.Error())
case mapping[row.TargetUserID] == "":
s.finishPush(ctx, row, pushStatusSkipped, nil, "缺少企微 userid 绑定")
default:
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, row.Content)
if err == nil {
s.finishPush(ctx, row, pushStatusSent, ptrTime(s.now()), "")
continue
}
logger.Warnf(ctx, "[TrainingScheduler] push notification %s to tenant %d user %s: %v",
row.ID, tenantID, row.TargetUserID, err)
if row.PushAttempts+1 >= s.cfg.MaxPushAttempts {
s.finishPush(ctx, row, pushStatusDead, nil, err.Error())
} else {
s.finishPush(ctx, row, pushStatusPending, nil, err.Error())
}
}
}
}
// finishPush records the delivery outcome of one outbox row. A retry keeps
// push_status='pending' and bumps attempts; pushed_at is only set on success.
func (s *TrainingScheduler) finishPush(ctx context.Context, row *claimedNotification, status string, pushedAt *time.Time, pushErr string) {
updates := map[string]interface{}{
"push_status": status,
"push_error": clipRunes(pushErr, 500),
"updated_at": time.Now(),
}
if status == pushStatusPending {
updates["push_attempts"] = row.PushAttempts + 1
} else {
updates["push_attempts"] = row.PushAttempts
}
if pushedAt != nil {
updates["pushed_at"] = *pushedAt
}
if err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
Where("id = ?", row.ID).Updates(updates).Error; err != nil {
logger.Warnf(ctx, "[TrainingScheduler] record push result %s: %v", row.ID, err)
}
}
// ---------------------------------------------------------------------------
// Test push (plumbing via the injected backend)
// ---------------------------------------------------------------------------
// PushTestNotification sends a direct WeCom test message so operators can
// verify credentials and the userid binding without waiting for a schedule.
func (s *TrainingScheduler) PushTestNotification(ctx context.Context, tenantID uint64, operatorUserID, targetUserID, content string) error {
client, err := s.backend.ClientForTenant(ctx, s.db, tenantID)
if err != nil {
return err
}
mapping, err := s.backend.TenantWecomUserIDs(ctx, s.db, tenantID, []string{targetUserID})
if err != nil {
return err
}
wecomUserID, ok := mapping[targetUserID]
if !ok {
return errors.New("该用户未绑定企微 userid(请在组织中心员工档案维护 wecom_userid)")
}
if strings.TrimSpace(content) == "" {
content = fmt.Sprintf("**【培训平台推送测试】**\n操作人:%s\n时间:%s\n收到本条消息即企微推送链路正常。",
operatorUserID, s.now().Format("2006-01-02 15:04"))
}
return client.SendMarkdown(ctx, []string{wecomUserID}, content)
}
// ---------------------------------------------------------------------------
// Content templates
// ---------------------------------------------------------------------------
func remindTitle(prefix string, course types.TrainingCourse) string {
if course.Name == "" {
return prefix
}
return fmt.Sprintf("%s:%s", prefix, course.Name)
}
// remindContent renders the WeCom markdown body of a session reminder; the
// maintain variant asks the lecturer to upload missing materials.
// [2026-11 需求] 结尾文案 footer 由配置中心「提醒推送文案」提供(缺省为内置默认)。
func remindContent(course types.TrainingCourse, sess *types.TrainingCourseSession, maintain bool, footer string) string {
var b strings.Builder
if maintain {
b.WriteString("**【课程维护提醒】**\n")
} else {
b.WriteString("**【培训开课提醒】**\n")
}
if course.Name != "" {
b.WriteString(fmt.Sprintf("> 课程:%s\n", course.Name))
}
if sess.StartAt != nil {
b.WriteString(fmt.Sprintf("> 开课时间:%s\n", sess.StartAt.Local().Format("2006-01-02 15:04")))
}
switch {
case sess.OnlineURL != "":
b.WriteString(fmt.Sprintf("> 参与方式:[线上课堂](%s)\n", sess.OnlineURL))
case sess.Location != "":
b.WriteString(fmt.Sprintf("> 地点:%s\n", sess.Location))
}
footer = strings.TrimSpace(footer)
if footer == "" {
if maintain {
footer = defaultLecturerMaintainFooter
} else {
footer = defaultLecturerOpenFooter
}
}
b.WriteString("\n" + footer)
return b.String()
}
@@ -0,0 +1,334 @@
package service
import (
"context"
"errors"
"path/filepath"
"strings"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// fakeWecomBackend serves a fake sender plus a userid mapping to the
// scheduler under test.
type fakeWecomBackend struct {
sender *fakePushSender
clientErr error
mapping map[string]string
lookupErr error
}
func (f *fakeWecomBackend) ClientForTenant(context.Context, *gorm.DB, uint64) (WecomPushSender, error) {
if f.clientErr != nil {
return nil, f.clientErr
}
return f.sender, nil
}
func (f *fakeWecomBackend) TenantWecomUserIDs(context.Context, *gorm.DB, uint64, []string) (map[string]string, error) {
if f.lookupErr != nil {
return nil, f.lookupErr
}
return f.mapping, nil
}
// fakePushSender records SendMarkdown calls for dispatcher assertions.
type fakePushSender struct {
sent [][]string
err error
}
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, _ string) error {
if f.err != nil {
return f.err
}
f.sent = append(f.sent, userIDs)
return nil
}
type trainingPushFixture struct {
db *gorm.DB
sched *TrainingScheduler
now time.Time
backend *fakeWecomBackend
tenantID uint64
}
func newTrainingPushFixture(t *testing.T) *trainingPushFixture {
t.Helper()
db, err := gorm.Open(
sqlite.Open(filepath.Join(t.TempDir(), "training_push.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent)},
)
require.NoError(t, err)
raw, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { _ = raw.Close() })
require.NoError(t, db.AutoMigrate(
&types.TrainingCourseSession{}, &types.TrainingCourse{}, &types.TrainingEnrollment{},
&types.OrgEmployee{}, &types.TrainingNotification{}, &types.TrainingMaterial{},
&types.TrainingRuleConfig{},
))
const tenantID = uint64(42)
now := time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)
backend := &fakeWecomBackend{sender: &fakePushSender{}, mapping: map[string]string{}}
sched := NewTrainingScheduler(db, backend)
sched.now = func() time.Time { return now }
return &trainingPushFixture{db: db, sched: sched, now: now, backend: backend, tenantID: tenantID}
}
// seedSession inserts a course + scheduled session; materials controls
// whether the course already has one material row. notifyMode 传空即
// immediate(默认,调度器不再生成学员 remind_tN,学员通知由保存名单钩子入队)。
func (f *trainingPushFixture) seedSession(t *testing.T, startOffset time.Duration, materials bool, lecturerID string) types.TrainingCourseSession {
t.Helper()
course := types.TrainingCourse{
ID: trainingNewID(), TenantID: f.tenantID, Name: "安全生产培训", Status: "published",
}
require.NoError(t, f.db.Create(&course).Error)
if materials {
require.NoError(t, f.db.Create(&types.TrainingMaterial{
ID: trainingNewID(), TenantID: f.tenantID, CourseID: course.ID, Name: "课件.pdf",
}).Error)
}
start := f.now.Add(startOffset)
sess := types.TrainingCourseSession{
ID: trainingNewID(), TenantID: f.tenantID, CourseID: course.ID,
StartAt: &start, Location: "三楼会议室", LecturerID: lecturerID,
Status: types.TrainingSessionScheduled,
}
require.NoError(t, f.db.Create(&sess).Error)
return sess
}
// setSessionNotifyMode 直接改写场次通知方式(day_before 用例用)。
func (f *trainingPushFixture) setSessionNotifyMode(t *testing.T, sessionID, mode string) {
t.Helper()
require.NoError(t, f.db.Model(&types.TrainingCourseSession{}).
Where("id = ?", sessionID).Update("notify_mode", mode).Error)
}
// seedEnrolledStudent wires enrollment → org_employee for userID.
func (f *trainingPushFixture) seedEnrolledStudent(t *testing.T, sessionID, userID, wecomUserid string) {
t.Helper()
member := types.OrgEmployee{
ID: trainingNewID(), TenantID: f.tenantID, UserID: userID, WecomUserid: wecomUserid,
}
require.NoError(t, f.db.Create(&member).Error)
require.NoError(t, f.db.Create(&types.TrainingEnrollment{
ID: trainingNewID(), TenantID: f.tenantID, SessionID: sessionID, MemberID: member.ID,
}).Error)
}
func (f *trainingPushFixture) notificationScenes(t *testing.T) map[string]int {
t.Helper()
var rows []*types.TrainingNotification
require.NoError(t, f.db.Find(&rows).Error)
out := map[string]int{}
for _, r := range rows {
out[r.TargetUserID+"\x00"+r.Scene]++
}
return out
}
func TestGenerateRemindersIdempotent(t *testing.T) {
f := newTrainingPushFixture(t)
// [2026-11 推学员] immediate 场次:调度器只发讲师 remind_tN;学员开课通知
// 由保存名单钩子入队(session_notice_student),调度器不再重复发学员 remind_tN。
sess := f.seedSession(t, 72*time.Hour, true, "lecturer-1") // T-3 due, has material
f.seedEnrolledStudent(t, sess.ID, "user-1", "wecom_u1")
// Two consecutive ticks must not duplicate rows (dedup index semantics).
require.NoError(t, f.sched.generateReminders(context.Background()))
require.NoError(t, f.sched.generateReminders(context.Background()))
scenes := f.notificationScenes(t)
require.NotContains(t, scenes, "user-1\x00"+types.TrainingRemindScene(3, false),
"student remind_tN removed: immediate sessions enqueue session_notice_student on roster save")
require.Equal(t, 1, scenes["lecturer-1\x00"+types.TrainingRemindScene(3, true)], "lecturer T-3 reminder once")
require.NotContains(t, scenes, "user-1\x00"+types.TrainingRemindScene(1, false), "T-1 not due yet")
// Lecturer row enters the WeCom outbox.
var row types.TrainingNotification
require.NoError(t, f.db.Where("scene = ?", types.TrainingRemindScene(3, true)).First(&row).Error)
require.Equal(t, pushStatusPending, row.PushStatus)
require.Equal(t, types.RefTypeCourseSession, row.RefType)
require.Equal(t, sess.ID, row.RefID)
require.Equal(t, "inapp", row.Channel)
}
// TestGenerateDayBeforeStudentNotice day_before 场次:T-1 且课件就绪时调度器
// 入队学员开课通知(session_notice_student);课件缺失时跳过,改期重排后仍幂等。
func TestGenerateDayBeforeStudentNotice(t *testing.T) {
f := newTrainingPushFixture(t)
sess := f.seedSession(t, 24*time.Hour, true, "lecturer-2") // T-1 due, has material
f.setSessionNotifyMode(t, sess.ID, types.TrainingNotifyModeDayBefore)
f.seedEnrolledStudent(t, sess.ID, "user-2", "wecom_u2")
require.NoError(t, f.sched.generateReminders(context.Background()))
require.NoError(t, f.sched.generateReminders(context.Background()))
scenes := f.notificationScenes(t)
require.Equal(t, 1, scenes["user-2\x00"+types.SceneSessionNoticeStudent],
"day_before student notice once at T-1")
require.NotContains(t, scenes, "user-2\x00"+types.TrainingRemindScene(1, false),
"student notice uses the single session_notice_student scene")
// 无课件的 day_before 场次:T-1 跳过,等上传课件后由 service 补推钩子兜底。
bare := f.seedSession(t, 24*time.Hour, false, "lecturer-3")
f.setSessionNotifyMode(t, bare.ID, types.TrainingNotifyModeDayBefore)
f.seedEnrolledStudent(t, bare.ID, "user-3", "wecom_u3")
require.NoError(t, f.sched.generateReminders(context.Background()))
scenes = f.notificationScenes(t)
require.NotContains(t, scenes, "user-3\x00"+types.SceneSessionNoticeStudent,
"missing courseware gates the day_before student notice")
}
func TestGenerateMaintainReminderOnlyWithoutMaterials(t *testing.T) {
f := newTrainingPushFixture(t)
// T+5d: outside T-3/T-1 remind windows, inside the 7-day maintain window.
f.seedSession(t, 5*24*time.Hour, false, "lecturer-1")
f.seedSession(t, 6*24*time.Hour, true, "lecturer-2")
require.NoError(t, f.sched.generateReminders(context.Background()))
scenes := f.notificationScenes(t)
require.Equal(t, 1, scenes["lecturer-1\x00"+types.SceneRemindLecturerMaintain],
"maintain reminder when no materials")
require.NotContains(t, scenes, "lecturer-2\x00"+types.SceneRemindLecturerMaintain,
"no maintain reminder when materials exist")
require.NotContains(t, scenes, "lecturer-1\x00"+types.TrainingRemindScene(3, true),
"T-3 not due for the 5d-out session")
}
func TestGeneratePushDisabledKeepsOutboxEmpty(t *testing.T) {
f := newTrainingPushFixture(t)
sess := f.seedSession(t, 72*time.Hour, true, "lecturer-1")
f.seedEnrolledStudent(t, sess.ID, "user-1", "wecom_u1")
require.NoError(t, f.db.Create(&types.TrainingRuleConfig{
ID: trainingNewID(), TenantID: f.tenantID, RuleKey: ruleKeyNotifyPushEnabled, RuleValue: types.JSON("false"),
}).Error)
require.NoError(t, f.sched.generateReminders(context.Background()))
var rows []*types.TrainingNotification
require.NoError(t, f.db.Find(&rows).Error)
require.NotEmpty(t, rows, "inapp rows still generated")
for _, r := range rows {
require.Empty(t, r.PushStatus, "push disabled → no outbox entry")
}
}
func TestDispatchTenantOutcomes(t *testing.T) {
t.Run("sent on success", 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: "s", Content: "c", 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", Content: "c"}})
var got types.TrainingNotification
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
require.Equal(t, pushStatusSent, got.PushStatus)
require.NotNil(t, got.PushedAt)
require.Equal(t, [][]string{{"wecom_u1"}}, f.backend.sender.sent)
})
t.Run("retry then dead at max attempts", func(t *testing.T) {
f := newTrainingPushFixture(t)
f.backend.mapping["user-1"] = "wecom_u1"
f.backend.sender.err = errors.New("wecom api error: code=1 msg=invalid userid")
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
TargetUserID: "user-1", Scene: "s", PushStatus: pushStatusSending, PushAttempts: 0}
require.NoError(t, f.db.Create(row).Error)
claim := &claimedNotification{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1"}
f.sched.dispatchTenant(context.Background(), f.tenantID, []*claimedNotification{claim})
var got types.TrainingNotification
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
require.Equal(t, pushStatusPending, got.PushStatus, "attempt 1 → back to pending")
require.Equal(t, 1, got.PushAttempts)
// Final allowed attempt fails → dead.
got.PushAttempts = f.sched.cfg.MaxPushAttempts - 1
got.PushStatus = pushStatusSending
require.NoError(t, f.db.Save(&got).Error)
claim.PushAttempts = got.PushAttempts
f.sched.dispatchTenant(context.Background(), f.tenantID, []*claimedNotification{claim})
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
require.Equal(t, pushStatusDead, got.PushStatus)
require.NotEmpty(t, got.PushError)
})
t.Run("skipped without userid binding", func(t *testing.T) {
f := newTrainingPushFixture(t)
// user-2 has no mapping entry.
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
TargetUserID: "user-2", Scene: "s", 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-2"}})
var got types.TrainingNotification
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
require.Equal(t, pushStatusSkipped, got.PushStatus)
require.Contains(t, got.PushError, "企微")
})
t.Run("skipped when client unavailable", func(t *testing.T) {
f := newTrainingPushFixture(t)
f.backend.mapping["user-1"] = "wecom_u1"
f.backend.clientErr = errors.New("未配置企微自建应用渠道")
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
TargetUserID: "user-1", Scene: "s", 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"}})
var got types.TrainingNotification
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
require.Equal(t, pushStatusSkipped, got.PushStatus)
require.Contains(t, got.PushError, "未配置企微自建应用渠道")
})
}
func TestPushTestNotification(t *testing.T) {
f := newTrainingPushFixture(t)
f.backend.mapping["user-1"] = "wecom_u1"
require.NoError(t, f.sched.PushTestNotification(context.Background(), f.tenantID, "op-1", "user-1", "hello"))
require.Equal(t, [][]string{{"wecom_u1"}}, f.backend.sender.sent)
err := f.sched.PushTestNotification(context.Background(), f.tenantID, "op-1", "user-missing", "")
require.Error(t, err)
require.Contains(t, err.Error(), "wecom_userid")
}
func TestRemindContent(t *testing.T) {
f := newTrainingPushFixture(t)
sess := f.seedSession(t, 72*time.Hour, false, "lecturer-1")
courses, err := f.sched.loadCourses(context.Background(), f.tenantID, []string{sess.CourseID})
require.NoError(t, err)
course := courses[sess.CourseID]
student := remindContent(course, &sess, false, defaultLecturerOpenFooter)
require.Contains(t, student, "安全生产培训")
require.Contains(t, student, sess.StartAt.Local().Format("2006-01-02 15:04"))
require.Contains(t, student, "三楼会议室")
maintain := remindContent(course, &sess, true, defaultLecturerMaintainFooter)
require.Contains(t, maintain, "课程维护提醒")
require.True(t, strings.Contains(maintain, "课件"), "maintain copy mentions materials")
}