feat(公告推送):配置中心-推送管理中增加一个手动推送功能
deploy-hxtesting / build-and-deploy (push) Successful in 1m19s

目的:为和信智汇学院有重要通知时可随时向用户手动推送重要信息使用
推送内容:标题、内容、落地页(均可自定义配置),默认值标题为“和信智汇学院”、内容为“重要通知”、落地页默认系统登录页如果已登录默认登录后系统页面
推送人员:默认全员通知,可根据部门、职位、具体人员进行自定义人员
推送时间:可立即推送也可设定定时推送!
This commit is contained in:
runny committed 2026-11-29 13:41:05 +08:00
1 parent 78e9787793
commit 61fb94744a
14 files changed
+1451 -2

No files matched your search

+58
View File
@@ -1427,6 +1427,8 @@ export interface TrainingNotification {
content: string content: string
ref_type: string ref_type: string
ref_id: string ref_id: string
/** 落地页地址(手动推送可自定义;000155 起通知行可携带)。 */
link_url?: string
sent_at: string sent_at: string
read_at: string | null read_at: string | null
} }
@@ -1550,6 +1552,62 @@ export const notifySessionStudents = (sessionId: string) =>
export const runWeeklyLecturerReminders = () => export const runWeeklyLecturerReminders = () =>
post<{ success: boolean; data: { queued: number } }>(`${base}/notifications/run-weekly`, {}) post<{ success: boolean; data: { queued: number } }>(`${base}/notifications/run-weekly`, {})
// ---- 手动推送([2026-11 需求] 配置中心 · 推送管理) ----
/** 手动推送默认文案(与后端 manualPushDefault* 逐字一致,弹窗预填空值兜底)。 */
export const MANUAL_PUSH_DEFAULT_TITLE = '和信智汇学院'
export const MANUAL_PUSH_DEFAULT_CONTENT = '重要通知'
/** TrainingPushTaskItem 手动推送任务行(镜像 internal/types.TrainingPushTaskItem)。 */
export interface TrainingPushTaskItem {
id: string
title: string
audience_mode: 'all' | 'dept' | 'post' | 'user'
/** 人员范围摘要(全员 / 按部门 财务部、人事部 / 按职位 课长 / 指定人员)。 */
audience_text: string
send_at: string
status: 'pending' | 'sending' | 'sent' | 'cancelled'
created_by: string
created_at: string
sent_at: string | null
sent_count: number
}
// TrainingManualPushResult 创建结果:任务行 + 创建时点人员数(定时任务发送时
// 按当时代名单重新解析)+ 是否定时。
export interface TrainingManualPushResult {
task: TrainingPushTaskItem
audience_count: number
scheduled: boolean
}
// createManualPush 手动推送一次通知(标题/内容/落地页可空走后端默认;人员范围
// 全员/按部门/按职位/按人员;send_at 为空 = 立即推送,ISO 字符串 = 定时)。
export const createManualPush = (payload: {
title?: string
content?: string
link_url?: string
audience_mode?: 'all' | 'dept' | 'post' | 'user'
dept_ids?: string[]
posts?: string[]
user_ids?: string[]
send_at?: string
}) =>
post<{ success: boolean; data: TrainingManualPushResult }>(
`${base}/notifications/manual-push`,
payload,
)
// listManualPushTasks 待发送定时任务列表(配置中心「手动推送」面板展示)。
export const listManualPushTasks = () =>
get<{ success: boolean; data: TrainingPushTaskItem[] }>(
`${base}/notifications/manual-push-tasks`,
)
// cancelManualPushTask 取消待发送定时任务(仅 pending 可取消)。
export const cancelManualPushTask = (id: string) =>
post<{ success: boolean }>(`${base}/notifications/manual-push-tasks/${enc(id)}/cancel`, {})
// ---- 内部小工具 ---- // ---- 内部小工具 ----
function enc(value: string) { function enc(value: string) {
@@ -139,9 +139,11 @@ const readCount = ref(0)
const trainingItems = ref<TrainingNotification[]>([]) const trainingItems = ref<TrainingNotification[]>([])
const TRAINING_NOTIFICATION_LIMIT = 50 const TRAINING_NOTIFICATION_LIMIT = 50
const trainingUnread = computed(() => trainingItems.value.filter(n => !n.read_at).length) const trainingUnread = computed(() => trainingItems.value.filter(n => !n.read_at).length)
// 培训通知按 ref_type 定位跳转页面(需求收集通知直达培训计划-年度需求收集) // 培训通知按 ref_type 定位跳转页面(需求收集通知直达培训计划-年度需求收集;
// 手动推送落地页自定义,点击打开通知行 link_url,缺省回培训首页)
const trainingLinkOf = (n: TrainingNotification) => { const trainingLinkOf = (n: TrainingNotification) => {
if (n.ref_type === 'plan') return '/platform/training/plan' if (n.ref_type === 'plan') return '/platform/training/plan'
if (n.ref_type === 'manual_push' && n.link_url) return n.link_url
return '/platform/training' return '/platform/training'
} }
const toTrainingAppNotification = (n: TrainingNotification): AppNotification => ({ const toTrainingAppNotification = (n: TrainingNotification): AppNotification => ({
@@ -375,6 +377,8 @@ const openInvitations = () => { panelVisible.value = false; dialogVisible.value
function navigate(link: string) { function navigate(link: string) {
panelVisible.value = false panelVisible.value = false
if (link.startsWith('/') && !link.startsWith('//')) void router.push(link) if (link.startsWith('/') && !link.startsWith('//')) void router.push(link)
// 绝对地址(手动推送自定义落地页可指向外部系统):新窗口打开,不打断当前会话
else if (/^https?:\/\//i.test(link)) window.open(link, '_blank', 'noopener')
} }
function openPending(item: PendingNotification) { navigate(item.link) } function openPending(item: PendingNotification) { navigate(item.link) }
@@ -152,8 +152,37 @@
</div> </div>
</t-tab-panel> </t-tab-panel>
<!-- 推送管理:推送提醒参数配置 + 推送投递记录 --> <!-- 推送管理:手动推送 + 推送提醒参数配置 + 推送投递记录 -->
<t-tab-panel value="notify" label="推送管理"> <t-tab-panel value="notify" label="推送管理">
<!-- 手动推送([2026-11 需求] 重要通知随时向全员/指定人员推送;定时任务发送前可取消) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">手动推送</span>
<div class="push-toolbar">
<t-button variant="outline" size="small" :loading="pushTasksLoading" @click="loadPushTasks">刷新</t-button>
<t-button theme="primary" size="small" @click="openManualPush">新建推送</t-button>
</div>
</div>
<div class="panel-box__sub">重要通知可随时向全员或指定人员手动推送:标题/内容/落地页可自定义,支持立即或定时推送,站内 + 企微双通道。</div>
<!-- 待发送定时任务:到达发送时间前可取消 -->
<template v-if="pushTasks.length">
<div class="push-task-title">待发送定时任务({{ pushTasks.length }})</div>
<t-table :data="pushTasks" :columns="pushTaskColumns" row-key="id" size="small" :loading="pushTasksLoading">
<template #send_at="{ row }">{{ fmtTime(row.send_at) }}</template>
<template #created_by="{ row }">{{ row.created_by || '—' }}</template>
<template #op="{ row }">
<t-popconfirm content="取消后该定时任务不再发送,确认取消?" theme="danger" @confirm="onCancelPushTask(row)">
<t-button variant="outline" theme="danger" size="small">取消</t-button>
</t-popconfirm>
</template>
</t-table>
</template>
<div v-else class="push-task-empty">暂无待发送的定时任务</div>
<div class="form-hint">
全员口径为空间全部在册成员(发送时按当时代名单解析,含新增账号);企微仅送达已绑定企微的同事,其余站内可达。推送明细在下方「推送记录」按场景「手动推送」查询。
</div>
</div>
<!-- 推送提醒配置(与业务规则同款点选式表单) --> <!-- 推送提醒配置(与业务规则同款点选式表单) -->
<div class="panel-box"> <div class="panel-box">
<div class="panel-box__header"> <div class="panel-box__header">
@@ -378,6 +407,94 @@
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button> <t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
</template> </template>
</t-dialog> </t-dialog>
<!-- 新建手动推送弹窗:标题/内容/落地页 + 人员范围(全员/部门/职位/人员) + 立即/定时 -->
<t-dialog v-model:visible="manualPushVisible" header="新建手动推送" width="640">
<t-form label-width="88px">
<t-form-item label="标题">
<t-input v-model="manualPushForm.title" placeholder="和信智汇学院" :maxlength="50" />
</t-form-item>
<t-form-item label="内容">
<t-textarea
v-model="manualPushForm.content"
:autosize="{ minRows: 3, maxRows: 6 }"
placeholder="重要通知"
:maxlength="500"
/>
</t-form-item>
<t-form-item label="落地页">
<t-input v-model="manualPushForm.linkUrl" placeholder="https://" clearable />
</t-form-item>
<t-form-item label="推送人员">
<div class="push-audience">
<t-radio-group v-model="manualPushForm.audienceMode" variant="default-filled" size="small">
<t-radio-button value="all">全员</t-radio-button>
<t-radio-button value="dept">按部门</t-radio-button>
<t-radio-button value="post">按职位</t-radio-button>
<t-radio-button value="user">按人员</t-radio-button>
</t-radio-group>
<t-select
v-if="manualPushForm.audienceMode === 'dept'"
v-model="manualPushForm.deptIds"
multiple
clearable
placeholder="选择部门,推送部门全部员工"
>
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
<t-select
v-else-if="manualPushForm.audienceMode === 'post'"
v-model="manualPushForm.posts"
multiple
filterable
clearable
placeholder="选择职位,推送该职位全部员工"
>
<t-option v-for="p in postOptions" :key="p" :value="p" :label="p" />
</t-select>
<t-select
v-else-if="manualPushForm.audienceMode === 'user'"
v-model="manualPushForm.userIds"
multiple
filterable
clearable
placeholder="从员工名册选择推送人员"
>
<t-option v-for="m in members" :key="m.user_id" :value="m.user_id" :label="memberLabel(m)" />
</t-select>
<div class="form-hint">
<template v-if="manualPushForm.audienceMode === 'all'">默认全员:空间全部在册成员,发送时按当时代名单解析(含新增账号)</template>
<template v-else>已解析 {{ resolvedAudienceCount }} 名成员;实际推送名单以发送时点为准</template>
</div>
</div>
</t-form-item>
<t-form-item label="推送时间">
<div class="push-audience">
<t-radio-group v-model="manualPushForm.timing" variant="default-filled" size="small">
<t-radio-button value="now">立即推送</t-radio-button>
<t-radio-button value="scheduled">定时推送</t-radio-button>
</t-radio-group>
<t-date-picker
v-if="manualPushForm.timing === 'scheduled'"
v-model="manualPushForm.sendAt"
class="push-task-time"
clearable
allow-input
enable-time-picker
format="YYYY-MM-DD HH:mm"
placeholder="选择发送时间(北京时间)"
/>
</div>
</t-form-item>
</t-form>
<div class="form-hint">
落地页留空默认本系统地址(未登录打开登录页,已登录进入系统首页);标题/内容留空按默认文案「和信智汇学院/重要通知」推送。
</div>
<template #footer>
<t-button variant="outline" :disabled="manualPushSending" @click="manualPushVisible = false">取消</t-button>
<t-button theme="primary" :loading="manualPushSending" @click="onSendManualPush">确认推送</t-button>
</template>
</t-dialog>
</div> </div>
</template> </template>
@@ -389,9 +506,17 @@ import {
DEFAULT_COURSE_CATEGORIES, DEFAULT_COURSE_CATEGORIES,
DEFAULT_DEMAND_COLLECT_CONTENT, DEFAULT_DEMAND_COLLECT_CONTENT,
DEFAULT_DEMAND_COLLECT_TITLE, DEFAULT_DEMAND_COLLECT_TITLE,
MANUAL_PUSH_DEFAULT_CONTENT,
MANUAL_PUSH_DEFAULT_TITLE,
ROLE_DICT_RULE_KEY, ROLE_DICT_RULE_KEY,
cancelManualPushTask,
createManualPush,
deleteTrainingTemplate, deleteTrainingTemplate,
fetchRoleDict, fetchRoleDict,
listDepts,
listManualPushTasks,
listMembers,
listPosts,
listRuleConfigs, listRuleConfigs,
listTrainingPushLogs, listTrainingPushLogs,
listTrainingTemplates, listTrainingTemplates,
@@ -400,9 +525,13 @@ import {
saveRuleConfig, saveRuleConfig,
seedRuleConfigs, seedRuleConfigs,
uploadTrainingTemplate, uploadTrainingTemplate,
type TrainingDept,
type TrainingManualPushResult,
type TrainingMember,
type TrainingPushLog, type TrainingPushLog,
type TrainingPushLogPage, type TrainingPushLogPage,
type TrainingPushLogStats, type TrainingPushLogStats,
type TrainingPushTaskItem,
type TrainingRoleDef, type TrainingRoleDef,
type TrainingRuleConfig, type TrainingRuleConfig,
type TrainingTemplateKey, type TrainingTemplateKey,
@@ -862,6 +991,7 @@ const PUSH_SCENE_OPTIONS = [
{ value: 'session_notice_student', label: '学员开课通知' }, { value: 'session_notice_student', label: '学员开课通知' },
{ value: 'remind_monthly_lecturer', label: '周一讲师提醒' }, { value: 'remind_monthly_lecturer', label: '周一讲师提醒' },
{ value: 'remind_lecturer_maintain', label: '课程维护提醒' }, { value: 'remind_lecturer_maintain', label: '课程维护提醒' },
{ value: 'manual_push', label: '手动推送' },
] ]
// 企微状态筛选项:pending 合并排队与投递中,in_site = 仅站内(push_status 空)。 // 企微状态筛选项:pending 合并排队与投递中,in_site = 仅站内(push_status 空)。
@@ -977,6 +1107,181 @@ const onRunWeekly = async () => {
} }
} }
// ---- 手动推送([2026-11 需求] 重要通知随时推送;定时任务发送前可取消) ----
const pushTasks = ref<TrainingPushTaskItem[]>([])
const pushTasksLoading = ref(false)
const pushTaskColumns = [
{ colKey: 'title', title: '标题', ellipsis: true },
{ colKey: 'audience_text', title: '推送人员', width: 200 },
{ colKey: 'send_at', title: '发送时间', width: 150 },
{ colKey: 'created_by', title: '创建人', width: 110 },
{ colKey: 'op', title: '操作', width: 80 },
]
const loadPushTasks = async () => {
pushTasksLoading.value = true
try {
const res = await listManualPushTasks()
pushTasks.value = unwrap<TrainingPushTaskItem[]>(res) || []
} finally {
pushTasksLoading.value = false
}
}
// onCancelPushTask 取消待发送定时任务;失败(已发送/已取消)后刷新列表纠偏。
const onCancelPushTask = async (row: TrainingPushTaskItem) => {
try {
await cancelManualPushTask(row.id)
MessagePlugin.success('已取消该定时推送')
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '取消失败,任务可能已发送')
} finally {
loadPushTasks()
}
}
// 名册数据(部门/职位/成员)首次打开弹窗懒加载;职位下拉以 posts 接口为准,
// 拉取失败回落成员档案去重(与课程管理参加人员选择器同口径)。
const depts = ref<TrainingDept[]>([])
const members = ref<TrainingMember[]>([])
const postOptions = ref<string[]>([])
const rostersLoaded = ref(false)
const memberLabel = (m: TrainingMember) =>
[m.user_name || m.employee_no, m.post, m.dept_name].filter(Boolean).join(' · ') || m.user_id
const loadRosters = async () => {
if (rostersLoaded.value) return
rostersLoaded.value = true
try {
const [deptRes, memberRes, postRes] = await Promise.all([
listDepts(),
listMembers({ page_size: 500 }),
listPosts(),
])
depts.value = unwrap<TrainingDept[]>(deptRes) || []
members.value = unwrap<{ items: TrainingMember[] }>(memberRes)?.items || []
postOptions.value =
unwrap<string[]>(postRes) ||
[...new Set(members.value.map((m) => m.post).filter(Boolean))].sort()
} catch {
/* 拉取失败保留空态,可手动搜索/选择 */
}
}
type ManualPushAudienceMode = 'all' | 'dept' | 'post' | 'user'
const manualPushVisible = ref(false)
const manualPushSending = ref(false)
const manualPushForm = ref({
title: MANUAL_PUSH_DEFAULT_TITLE,
content: MANUAL_PUSH_DEFAULT_CONTENT,
linkUrl: '',
audienceMode: 'all' as ManualPushAudienceMode,
deptIds: [] as string[],
posts: [] as string[],
userIds: [] as string[],
timing: 'now' as 'now' | 'scheduled',
sendAt: '',
})
// resolvedAudienceCount 按部门/职位从名册联集已解析成员数;按人员=已选人数
// (全员不预览,后端发送时按当时代名单解析)。
const resolvedAudienceCount = computed(() => {
const f = manualPushForm.value
if (f.audienceMode === 'user') return new Set(f.userIds).size
const picked = f.audienceMode === 'dept' ? f.deptIds : f.posts
if (!picked.length) return 0
const matched = members.value.filter((m) =>
f.audienceMode === 'dept' ? picked.includes(m.dept_id) : picked.includes(m.post),
)
return new Set(matched.map((m) => m.user_id)).size
})
// defaultLandingURL 落地页默认值:配置中心「推送链接基址」优先(多入口/内外网
// 部署权威域名),否则当前访问 origin —— 站点根路径未登录打开登录页,已登录进系统首页。
const defaultLandingURL = () => {
const base = String(ruleValues.value.notify_link_base_url?.base_url || '').trim()
return base || window.location.origin
}
const openManualPush = () => {
manualPushForm.value = {
title: MANUAL_PUSH_DEFAULT_TITLE,
content: MANUAL_PUSH_DEFAULT_CONTENT,
linkUrl: defaultLandingURL(),
audienceMode: 'all',
deptIds: [],
posts: [],
userIds: [],
timing: 'now',
sendAt: '',
}
manualPushVisible.value = true
loadRosters()
}
const onSendManualPush = async () => {
const f = manualPushForm.value
if (f.audienceMode === 'dept' && !f.deptIds.length) {
MessagePlugin.warning('请选择要推送的部门')
return
}
if (f.audienceMode === 'post' && !f.posts.length) {
MessagePlugin.warning('请选择要推送的职位')
return
}
if (f.audienceMode === 'user' && !f.userIds.length) {
MessagePlugin.warning('请选择要推送的人员')
return
}
let sendAt: string | undefined
if (f.timing === 'scheduled') {
const parsed = new Date(f.sendAt.trim().replace(' ', 'T'))
if (!f.sendAt.trim() || Number.isNaN(parsed.getTime())) {
MessagePlugin.warning('请选择定时发送时间')
return
}
if (parsed.getTime() <= Date.now()) {
MessagePlugin.warning('定时发送时间必须晚于当前时刻')
return
}
sendAt = parsed.toISOString()
}
manualPushSending.value = true
try {
const res = await createManualPush({
title: f.title.trim(),
content: f.content.trim(),
link_url: f.linkUrl.trim(),
audience_mode: f.audienceMode,
dept_ids: f.deptIds,
posts: f.posts,
user_ids: f.userIds,
send_at: sendAt,
})
const result = unwrap<TrainingManualPushResult>(res)
if (result?.scheduled) {
MessagePlugin.success(
`定时推送已设定:${fmtTime(result.task.send_at)} 自动向 ${result.audience_count} 人推送,发送前可在上方取消`,
)
} else {
MessagePlugin.success(
`已推送 ${result?.audience_count ?? 0} 人(站内 + 企业微信;未绑定企微的同事仅站内送达,明细见下方推送记录)`,
)
}
manualPushVisible.value = false
loadPushTasks()
loadPushLogs()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '推送失败,请稍后重试')
} finally {
manualPushSending.value = false
}
}
const isDirty = (key: string) => JSON.stringify(ruleValues.value[key]) !== savedSnapshot.value[key] const isDirty = (key: string) => JSON.stringify(ruleValues.value[key]) !== savedSnapshot.value[key]
const weightSum = computed(() => { const weightSum = computed(() => {
@@ -1129,6 +1434,7 @@ onMounted(() => {
loadRoles() loadRoles()
loadTemplates() loadTemplates()
loadPushLogs() loadPushLogs()
loadPushTasks()
}) })
</script> </script>
@@ -1410,4 +1716,40 @@ onMounted(() => {
white-space: nowrap; white-space: nowrap;
color: var(--td-error-color); color: var(--td-error-color);
} }
/* 手动推送:待发送定时任务小表与弹窗表单([2026-11 需求]) */
.push-task-title {
margin: 12px 0 8px;
font-weight: 600;
font-size: var(--app-text-sm);
}
.push-task-empty {
margin-top: 12px;
padding: 10px 12px;
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-container);
border: 1px dashed var(--td-component-border);
border-radius: var(--td-radius-default);
}
.push-audience {
width: 100%;
display: flex;
flex-direction: column;
gap: 8px;
.t-select {
width: 100%;
}
.form-hint {
margin-top: 0;
}
}
.push-task-time {
width: 100%;
}
</style> </style>
@@ -0,0 +1,209 @@
package repository
import (
"context"
"time"
"academy/internal/types"
)
// 手动推送任务数据访问([2026-11 需求] 配置中心 · 推送管理「手动推送」)。
// 任务表 tr_push_tasks 只存推送意图,扇出到 tr_notifications 由 service 层
// 完成;到期认领用 compare-and-set(pending→sending),多实例安全且 SQLite
// 仓库测试可跑(不走 SKIP LOCKED);sending 超时回收由调度器按
// sendingReclaimAfter 统一处理。
// CreatePushTask 落一条推送意图(立即/定时共用,立即任务落库即扇出后置 sent)。
func (r *trainingRepository) CreatePushTask(ctx context.Context, task *types.TrainingPushTask) error {
return r.db.WithContext(ctx).Create(task).Error
}
// GetPushTask 取租户内单条任务。
func (r *trainingRepository) GetPushTask(ctx context.Context, tenantID uint64, id string) (*types.TrainingPushTask, error) {
var task types.TrainingPushTask
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
First(&task).Error; err != nil {
return nil, err
}
return &task, nil
}
// ListPushTasksByStatus 按状态取任务(发送时间升序,待发送定时任务展示)。
func (r *trainingRepository) ListPushTasksByStatus(ctx context.Context, tenantID uint64, status string, limit int) ([]*types.TrainingPushTask, error) {
if limit <= 0 || limit > 100 {
limit = 100
}
var items []*types.TrainingPushTask
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND status = ? AND deleted_at IS NULL", tenantID, status).
Order("send_at ASC, id ASC").Limit(limit).
Find(&items).Error
return items, err
}
// ClaimDuePushTasks 扫描到期任务(send_at<=now,跨租户)并逐条 CAS 认领:
// UPDATE ... WHERE status='pending' 影响 0 行 = 已被其他实例抢走,跳过。
func (r *trainingRepository) ClaimDuePushTasks(ctx context.Context, now time.Time, limit int) ([]*types.TrainingPushTask, error) {
if limit <= 0 {
limit = 50
}
var due []*types.TrainingPushTask
if err := r.db.WithContext(ctx).
Where("status = ? AND send_at <= ? AND deleted_at IS NULL", types.PushTaskStatusPending, now).
Order("send_at ASC").Limit(limit).
Find(&due).Error; err != nil {
return nil, err
}
claimed := make([]*types.TrainingPushTask, 0, len(due))
for _, task := range due {
res := r.db.WithContext(ctx).Model(&types.TrainingPushTask{}).
Where("id = ? AND status = ?", task.ID, types.PushTaskStatusPending).
Updates(map[string]interface{}{
"status": types.PushTaskStatusSending,
"updated_at": time.Now(),
})
if res.Error != nil {
return claimed, res.Error
}
if res.RowsAffected == 0 {
continue // 另一实例已认领
}
claimed = append(claimed, task)
}
return claimed, nil
}
// MarkPushTaskSent 记录扇出完成(仅 sending 态可落,防并发双写)。
func (r *trainingRepository) MarkPushTaskSent(ctx context.Context, id string, sentCount int, sentAt time.Time) error {
return r.db.WithContext(ctx).Model(&types.TrainingPushTask{}).
Where("id = ? AND status = ?", id, types.PushTaskStatusSending).
Updates(map[string]interface{}{
"status": types.PushTaskStatusSent,
"sent_count": sentCount,
"sent_at": sentAt,
"updated_at": time.Now(),
}).Error
}
// RequeueStalePushTasks 把 sending 超时的任务(实例扇出中途崩溃)放回 pending
// 重投;通知行按 (target,scene,ref_id) 唯一索引幂等,重跑只补漏不重发。
func (r *trainingRepository) RequeueStalePushTasks(ctx context.Context, staleBefore time.Time) (int64, error) {
res := r.db.WithContext(ctx).Model(&types.TrainingPushTask{}).
Where("status = ? AND updated_at < ?", types.PushTaskStatusSending, staleBefore).
Updates(map[string]interface{}{
"status": types.PushTaskStatusPending,
"updated_at": time.Now(),
})
return res.RowsAffected, res.Error
}
// RequeuePushTask 把单条 sending 任务放回 pending(扇出瞬时失败,调度器下轮重试)。
func (r *trainingRepository) RequeuePushTask(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Model(&types.TrainingPushTask{}).
Where("id = ? AND status = ?", id, types.PushTaskStatusSending).
Updates(map[string]interface{}{
"status": types.PushTaskStatusPending,
"updated_at": time.Now(),
}).Error
}
// CancelPushTask 取消待发送任务;返回是否取消成功(已发送/已认领不可取消)。
func (r *trainingRepository) CancelPushTask(ctx context.Context, tenantID uint64, id string) (bool, error) {
res := r.db.WithContext(ctx).Model(&types.TrainingPushTask{}).
Where("tenant_id = ? AND id = ? AND status = ? AND deleted_at IS NULL",
tenantID, id, types.PushTaskStatusPending).
Updates(map[string]interface{}{
"status": types.PushTaskStatusCancelled,
"updated_at": time.Now(),
})
return res.Error == nil && res.RowsAffected > 0, res.Error
}
// ListManualPushAudience 解析手动推送人员名单(user_id 去重,保持稳定顺序):
// - all:空间全部 active 成员(users JOIN tenant_members,ListTenantUsers 同口径,
// 含未入员工名册的账号,站内通知可达;企微投递时无绑定者自然 skipped)
// - dept / post:org_employees 按 dept_id / post 过滤(active 档案)
// - user:直接采用指定名单(仍按空间成员口径过滤,防越租户投递)
func (r *trainingRepository) ListManualPushAudience(
ctx context.Context, tenantID uint64, mode string, deptIDs, posts, userIDs []string,
) ([]string, error) {
clean := func(list []string) []string {
out := make([]string, 0, len(list))
seen := map[string]bool{}
for _, id := range list {
if id == "" || seen[id] {
continue
}
seen[id] = true
out = append(out, id)
}
return out
}
switch mode {
case types.PushTaskAudienceDept, types.PushTaskAudiencePost:
ids := clean(deptIDs)
column, values := "dept_id", ids
if mode == types.PushTaskAudiencePost {
column, values = "post", clean(posts)
}
if len(values) == 0 {
return nil, nil
}
var rows []types.OrgEmployee
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND "+column+" IN ? AND status = 'active' AND user_id <> '' AND deleted_at IS NULL",
tenantID, values).
Find(&rows).Error; err != nil {
return nil, err
}
out := make([]string, 0, len(rows))
seen := map[string]bool{}
for _, m := range rows {
if seen[m.UserID] {
continue
}
seen[m.UserID] = true
out = append(out, m.UserID)
}
return out, nil
case types.PushTaskAudienceUser:
ids := clean(userIDs)
if len(ids) == 0 {
return nil, nil
}
// 指定名单仍限定在本空间成员内(与全员同口径),避免误投其他空间用户。
var rows []struct{ ID string }
if err := r.db.WithContext(ctx).Table("users u").
Select("u.id").
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
Where("u.id IN ? AND u.is_active = TRUE AND u.deleted_at IS NULL", ids).
Scan(&rows).Error; err != nil {
return nil, err
}
return clean(func() []string {
out := make([]string, 0, len(rows))
for _, row := range rows {
out = append(out, row.ID)
}
return out
}()), nil
default: // all
var rows []struct{ ID string }
if err := r.db.WithContext(ctx).Table("users u").
Select("u.id").
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
Order("u.created_at ASC").
Scan(&rows).Error; err != nil {
return nil, err
}
out := make([]string, 0, len(rows))
for _, row := range rows {
out = append(out, row.ID)
}
return out, nil
}
}
@@ -0,0 +1,306 @@
package service
// 手动推送([2026-11 需求] 配置中心 · 推送管理):和信智汇学院重要通知随时
// 向用户手动推送。一次推送 = 一条 tr_push_tasks 意图(标题/内容/落地页 +
// 人员范围 + 发送时间)+ 发送时点按当时代名单扇出 tr_notifications
// (scene=manual_push),站内铃铛即时可见,企微走既有外箱投递
// (training_scheduler dispatchPending);明细自动进入「推送记录」。
// 立即推送在接口内同步扇出;定时推送由调度器 tick 认领到期任务投递
// (见 training_scheduler.go dispatchManualPushTasks)。
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"academy/internal/application/repository"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
)
// 手动推送默认文案(前端弹窗预填同款,后端对空值兜底)。
const (
manualPushDefaultTitle = "和信智汇学院"
manualPushDefaultContent = "重要通知"
)
// manualPushClaimBatch caps tasks claimed per scheduler tick.
const manualPushClaimBatch = 50
// CreateManualPush 创建一次手动推送(人事/课长,配置中心「新建推送」弹窗):
// - 标题/内容为空按默认文案兜底(和信智汇学院 / 重要通知);
// - 落地页经 notify_link_base_url 覆盖归一(未登录打开登录页、已登录进系统
// 首页即站点根路径;前端默认预填 origin,非法值退回空 = 不带链接);
// - 人员范围 mode=all 缺省;创建时点解析一次做非空校验与人数预估,
// 发送时点(立即或定时到期)重新解析 —— 全员/部门口径天然覆盖新增账号;
// - SendAt 为空或不早于当前时刻 = 立即推送(同步扇出后置 sent);
// 否则落 pending 任务由调度器在 send_at 到期后投递。
func (s *trainingService) CreateManualPush(
ctx context.Context, tenantID uint64, operatorID string, req *types.TrainingManualPushRequest,
) (*types.TrainingManualPushResult, error) {
if req == nil {
return nil, errors.NewBadRequestError("请求参数不合法")
}
title := strings.TrimSpace(req.Title)
if title == "" {
title = manualPushDefaultTitle
}
content := strings.TrimSpace(req.Content)
if content == "" {
content = manualPushDefaultContent
}
linkURL := normalizeLinkBase(s.loadLinkBaseOverride(ctx, tenantID), req.LinkURL)
mode := req.AudienceMode
switch mode {
case types.PushTaskAudienceAll, types.PushTaskAudienceDept, types.PushTaskAudiencePost, types.PushTaskAudienceUser:
default:
mode = types.PushTaskAudienceAll
}
// 创建时点预解析人员:非法空名单在入口即报错,避免落一条永远发不出去的任务。
audience, err := s.repo.ListManualPushAudience(ctx, tenantID, mode, req.DeptIDs, req.Posts, req.UserIDs)
if err != nil {
return nil, err
}
if len(audience) == 0 {
return nil, errors.NewBadRequestError("推送人员为空,请调整人员范围")
}
task := &types.TrainingPushTask{
ID: trainingNewID(), TenantID: tenantID,
Title: clipRunes(title, 255), Content: content, LinkURL: linkURL,
AudienceMode: mode,
SendAt: time.Now(),
Status: types.PushTaskStatusSending,
CreatedBy: operatorID,
}
task.DeptIDs = pushTaskJSONColumn(req.DeptIDs)
task.Posts = pushTaskJSONColumn(req.Posts)
task.UserIDs = pushTaskJSONColumn(req.UserIDs)
scheduled := req.SendAt != nil && req.SendAt.After(time.Now())
if scheduled {
task.SendAt = *req.SendAt
task.Status = types.PushTaskStatusPending
}
if err := s.repo.CreatePushTask(ctx, task); err != nil {
return nil, err
}
result := &types.TrainingManualPushResult{
Task: s.pushTaskItem(ctx, task),
AudienceCount: len(audience),
Scheduled: scheduled,
}
if scheduled {
return result, nil
}
// 立即推送:同步扇出;失败把任务放回 pending 由调度器兜底重试(前端已报错,
// 用户可在「待发送定时任务」里看到并取消)。
sent, err := s.fanOutManualPush(ctx, task)
if err != nil {
logger.Warnf(ctx, "[ManualPush] immediate fanout task %s: %v", task.ID, err)
if requeueErr := s.repo.RequeuePushTask(ctx, task.ID); requeueErr != nil {
logger.Warnf(ctx, "[ManualPush] requeue task %s: %v", task.ID, requeueErr)
}
return nil, err
}
sentAt := time.Now()
if err := s.repo.MarkPushTaskSent(ctx, task.ID, sent, sentAt); err != nil {
logger.Warnf(ctx, "[ManualPush] mark task %s sent: %v", task.ID, err)
}
result.Task.Status = types.PushTaskStatusSent
result.Task.SentAt = &sentAt
result.Task.SentCount = sent
result.AudienceCount = sent
return result, nil
}
// fanOutManualPush 把任务扇出成逐人通知行(立即推送与调度器投递共用):
// 发送时点重新解析人员名单;notify_push_enabled 关闭时仅站内(push_status 空,
// 不进企微外箱);(tenant,target,scene,ref_id) 唯一索引 + ON CONFLICT DO
// NOTHING 保证调度器重试只补漏不重发。返回新入箱条数。
func (s *trainingService) fanOutManualPush(ctx context.Context, task *types.TrainingPushTask) (int, error) {
audience, err := s.repo.ListManualPushAudience(ctx, task.TenantID, task.AudienceMode,
pushTaskJSONStrings(task.DeptIDs), pushTaskJSONStrings(task.Posts), pushTaskJSONStrings(task.UserIDs))
if err != nil {
return 0, err
}
if len(audience) == 0 {
return 0, nil
}
status := ""
if s.loadPushEnabled(ctx, task.TenantID) {
status = pushStatusPending
}
now := time.Now()
rows := make([]*types.TrainingNotification, 0, len(audience))
for _, uid := range audience {
rows = append(rows, &types.TrainingNotification{
ID: trainingNewID(), TenantID: task.TenantID,
TargetUserID: uid, Channel: "inapp", Scene: types.SceneManualPush,
Title: task.Title, Content: task.Content,
RefType: types.RefTypeManualPush, RefID: task.ID,
LinkURL: task.LinkURL,
SentAt: now, PushStatus: status,
})
}
if err := s.repo.CreateNotifications(ctx, rows); err != nil {
return 0, err
}
logger.Infof(ctx, "[ManualPush] task %s tenant %d fanned out %d notifications (push=%v)",
task.ID, task.TenantID, len(rows), status != "")
return len(rows), nil
}
// ListManualPushTasks 待发送定时任务列表(配置中心「手动推送」面板展示),
// 附人员范围摘要与创建人姓名。
func (s *trainingService) ListManualPushTasks(ctx context.Context, tenantID uint64) ([]*types.TrainingPushTaskItem, error) {
tasks, err := s.repo.ListPushTasksByStatus(ctx, tenantID, types.PushTaskStatusPending, manualPushClaimBatch)
if err != nil {
return nil, err
}
items := make([]*types.TrainingPushTaskItem, 0, len(tasks))
creatorIDs := make([]string, 0, len(tasks))
for _, task := range tasks {
items = append(items, s.pushTaskItem(ctx, task))
if task.CreatedBy != "" {
creatorIDs = append(creatorIDs, task.CreatedBy)
}
}
if len(creatorIDs) == 0 {
return items, nil
}
members, _ := s.repo.ListMembersByUserIDs(ctx, tenantID, creatorIDs)
byUser := map[string]*types.TrainingMember{}
for _, m := range members {
byUser[m.UserID] = m
}
for i, task := range tasks {
if m := byUser[task.CreatedBy]; m != nil {
items[i].CreatedBy = m.UserName
}
}
return items, nil
}
// CancelManualPushTask 取消待发送任务(仅 pending 可取消;已认领/已发送/已取消
// 报错,前端提示刷新)。
func (s *trainingService) CancelManualPushTask(ctx context.Context, tenantID uint64, id string) error {
if _, err := s.repo.GetPushTask(ctx, tenantID, id); err != nil {
return errors.NewNotFoundError("推送任务不存在")
}
ok, err := s.repo.CancelPushTask(ctx, tenantID, id)
if err != nil {
return err
}
if !ok {
return errors.NewBadRequestError("任务已发送或已取消,无法取消")
}
return nil
}
// pushTaskItem 组装列表行:人员范围摘要(全员 / 按部门:名称 / 按职位:原文 /
// 指定人员)+ 创建人(user_id 先占位,ListManualPushTasks 统一映射姓名)。
func (s *trainingService) pushTaskItem(ctx context.Context, task *types.TrainingPushTask) *types.TrainingPushTaskItem {
item := &types.TrainingPushTaskItem{
ID: task.ID,
Title: task.Title,
AudienceMode: task.AudienceMode,
SendAt: task.SendAt,
Status: task.Status,
CreatedBy: task.CreatedBy,
CreatedAt: task.CreatedAt,
SentAt: task.SentAt,
SentCount: task.SentCount,
}
switch task.AudienceMode {
case types.PushTaskAudienceDept:
ids := pushTaskJSONStrings(task.DeptIDs)
item.AudienceText = "按部门 " + strings.Join(s.deptNames(ctx, task.TenantID, ids), "、")
case types.PushTaskAudiencePost:
item.AudienceText = "按职位 " + strings.Join(pushTaskJSONStrings(task.Posts), "、")
case types.PushTaskAudienceUser:
item.AudienceText = "指定人员"
default:
item.AudienceText = "全员"
}
return item
}
// deptNames 部门 id → 名称(组织中心不可用时回落 id 原文,不阻断列表)。
func (s *trainingService) deptNames(ctx context.Context, tenantID uint64, ids []string) []string {
if len(ids) == 0 {
return nil
}
byID := map[string]string{}
if s.org != nil {
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
byID[d.ID] = d.Name
}
}
}
out := make([]string, 0, len(ids))
for _, id := range ids {
if name := byID[id]; name != "" {
out = append(out, name)
} else {
out = append(out, id)
}
}
return out
}
// pushTaskJSONColumn 编码请求名单为 jsonb 列值(空列表落 '[]')。
func pushTaskJSONColumn(list []string) types.JSON {
if len(list) == 0 {
return types.JSON([]byte("[]"))
}
raw, err := json.Marshal(list)
if err != nil {
return types.JSON([]byte("[]"))
}
return types.JSON(raw)
}
// pushTaskJSONStrings 解码 jsonb 名单列(容错回落空列表)。
func pushTaskJSONStrings(raw types.JSON) []string {
return trainingJSONStrings(string(raw))
}
// ---------------------------------------------------------------------------
// 调度器投递(training scheduler tick 步骤)
// ---------------------------------------------------------------------------
// dispatchManualPushTasks 认领到期手动推送任务并扇出(send_at<=now,pending 态;
// CAS 认领多实例安全)。先回收 sending 超时的任务(实例扇出中途崩溃,唯一索引
// 幂等只补漏);扇出瞬时失败的任务放回 pending 下轮重试。
func (s *TrainingScheduler) dispatchManualPushTasks(ctx context.Context) error {
svc := &trainingService{repo: repository.NewTrainingRepository(s.db)}
if stale, err := svc.repo.RequeueStalePushTasks(ctx, s.now().Add(-sendingReclaimAfter)); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] reclaim stale push tasks: %v", err)
} else if stale > 0 {
logger.Infof(ctx, "[TrainingScheduler] reclaimed %d stale manual push tasks", stale)
}
claimed, err := svc.repo.ClaimDuePushTasks(ctx, s.now(), manualPushClaimBatch)
if err != nil {
return fmt.Errorf("claim due push tasks: %w", err)
}
for _, task := range claimed {
sent, err := svc.fanOutManualPush(ctx, task)
if err != nil {
logger.Warnf(ctx, "[TrainingScheduler] manual push task %s: %v", task.ID, err)
if requeueErr := svc.repo.RequeuePushTask(ctx, task.ID); requeueErr != nil {
logger.Warnf(ctx, "[TrainingScheduler] requeue push task %s: %v", task.ID, requeueErr)
}
continue
}
if err := svc.repo.MarkPushTaskSent(ctx, task.ID, sent, s.now()); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] mark push task %s sent: %v", task.ID, err)
}
}
return nil
}
@@ -0,0 +1,266 @@
package service
import (
"context"
"path/filepath"
"testing"
"time"
"academy/internal/application/repository"
"academy/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// newManualPushFixture 构建 sqlite + 真实仓储的 trainingService 与调度器,
// 专测手动推送(创建/扇出/定时投递/取消)与人员范围解析。
func newManualPushFixture(t *testing.T) (*trainingService, *TrainingScheduler, *gorm.DB, uint64) {
t.Helper()
db, err := gorm.Open(
sqlite.Open(filepath.Join(t.TempDir(), "training_manual_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.User{}, &types.TenantMember{}, &types.OrgEmployee{},
&types.TrainingNotification{}, &types.TrainingRuleConfig{}, &types.TrainingPushTask{},
))
const tenantID = uint64(42)
svc := &trainingService{repo: repository.NewTrainingRepository(db), db: db}
sched := &TrainingScheduler{
db: db, cfg: DefaultTrainingSchedulerConfig(), now: time.Now,
}
return svc, sched, db, tenantID
}
// seedManualPushOrg 种入空间成员与员工名册:
// - u-all / u-dept / u-post 为 tenant 42 active 成员(全员口径)
// - u-outsider 有账号无成员关系(全员不可见)
// - u-inactive 成员关系 status=inactive(全员不可见)
// - u-noroster 成员存在但无员工档案(dept/post 过滤不可见,全员可见)
func seedManualPushOrg(t *testing.T, db *gorm.DB, tenantID uint64) {
t.Helper()
for _, id := range []string{"u-all", "u-dept", "u-post", "u-outsider", "u-inactive", "u-noroster"} {
require.NoError(t, db.Create(&types.User{
ID: id, Username: id, Email: id + "@x.local", TenantID: tenantID,
IsActive: true, CreatedAt: time.Now(), UpdatedAt: time.Now(),
}).Error)
}
for _, m := range []*types.TenantMember{
{UserID: "u-all", TenantID: tenantID, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()},
{UserID: "u-dept", TenantID: tenantID, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()},
{UserID: "u-post", TenantID: tenantID, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()},
{UserID: "u-outsider", TenantID: 99, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()},
{UserID: "u-inactive", TenantID: tenantID, Status: "inactive", JoinedAt: time.Now()},
{UserID: "u-noroster", TenantID: tenantID, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()},
} {
require.NoError(t, db.Create(m).Error)
}
for _, e := range []*types.OrgEmployee{
{ID: "e-all", TenantID: tenantID, UserID: "u-all", DeptID: "d-1", Post: "工程师", Status: "active"},
{ID: "e-dept", TenantID: tenantID, UserID: "u-dept", DeptID: "d-1", Post: "工程师", Status: "active"},
{ID: "e-post", TenantID: tenantID, UserID: "u-post", DeptID: "d-2", Post: "课长", Status: "active"},
{ID: "e-out", TenantID: 99, UserID: "u-outsider", DeptID: "d-1", Post: "工程师", Status: "active"},
{ID: "e-left", TenantID: tenantID, UserID: "u-inactive", DeptID: "d-1", Post: "工程师", Status: "inactive"},
} {
require.NoError(t, db.Create(&e).Error)
}
}
// 人员范围解析:全员=空间全部 active 成员(含无档案账号,排除他空间与
// 非活跃);部门/职位按员工档案过滤;指定人员限定在本空间成员内。
func TestManualPushAudienceResolution(t *testing.T) {
svc, _, _, tenantID := newManualPushFixture(t)
seedManualPushOrg(t, svc.db, tenantID)
ctx := context.Background()
all, err := svc.repo.ListManualPushAudience(ctx, tenantID, types.PushTaskAudienceAll, nil, nil, nil)
require.NoError(t, err)
require.ElementsMatch(t, []string{"u-all", "u-dept", "u-post", "u-noroster"}, all,
"全员应含无档案成员,排除他空间/非活跃账号")
dept, err := svc.repo.ListManualPushAudience(ctx, tenantID, types.PushTaskAudienceDept, []string{"d-1"}, nil, nil)
require.NoError(t, err)
require.ElementsMatch(t, []string{"u-all", "u-dept"}, dept, "部门过滤按档案 active 行,排除他空间与离职")
post, err := svc.repo.ListManualPushAudience(ctx, tenantID, types.PushTaskAudiencePost, nil, []string{"课长"}, nil)
require.NoError(t, err)
require.ElementsMatch(t, []string{"u-post"}, post)
mixed, err := svc.repo.ListManualPushAudience(ctx, tenantID, types.PushTaskAudienceUser, nil, nil,
[]string{"u-all", "u-outsider", "u-all", "", "u-dept"})
require.NoError(t, err)
require.ElementsMatch(t, []string{"u-all", "u-dept"}, mixed,
"指定人员去重并限定本空间成员,他空间账号不可投递")
empty, err := svc.repo.ListManualPushAudience(ctx, tenantID, types.PushTaskAudienceDept, []string{"d-none"}, nil, nil)
require.NoError(t, err)
require.Empty(t, empty)
}
// 立即推送:默认文案兜底 + 落地页归一落库 + 任务置 sent + 逐人通知行
// (scene=manual_push,推送开关开启时进企微外箱 pending)。
func TestCreateManualPushImmediate(t *testing.T) {
svc, _, _, tenantID := newManualPushFixture(t)
seedManualPushOrg(t, svc.db, tenantID)
ctx := context.Background()
result, err := svc.CreateManualPush(ctx, tenantID, "op-1", &types.TrainingManualPushRequest{
LinkURL: "https://kbt.example.com/",
})
require.NoError(t, err)
require.False(t, result.Scheduled)
require.Equal(t, 4, result.AudienceCount, "全员=4 名 active 成员")
require.Equal(t, manualPushDefaultTitle, result.Task.Title, "空标题回落默认「和信智汇学院」")
var task types.TrainingPushTask
require.NoError(t, svc.db.Where("tenant_id = ?", tenantID).First(&task).Error)
require.Equal(t, types.PushTaskStatusSent, task.Status)
require.Equal(t, manualPushDefaultContent, task.Content, "空内容回落默认「重要通知」")
require.Equal(t, "https://kbt.example.com", task.LinkURL, "尾部斜杠应归一化")
require.Equal(t, "op-1", task.CreatedBy)
require.NotNil(t, task.SentAt)
require.Equal(t, 4, task.SentCount)
var rows []types.TrainingNotification
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Len(t, rows, 4)
for _, row := range rows {
require.Equal(t, types.RefTypeManualPush, row.RefType)
require.Equal(t, task.ID, row.RefID)
require.Equal(t, "https://kbt.example.com", row.LinkURL)
require.Equal(t, "pending", row.PushStatus, "推送开关默认开启,行应进企微外箱")
}
// 空名单入口即报错,不落任务
_, err = svc.CreateManualPush(ctx, tenantID, "op-1", &types.TrainingManualPushRequest{
AudienceMode: types.PushTaskAudienceDept, DeptIDs: []string{"d-none"},
})
require.Error(t, err)
require.Contains(t, err.Error(), "推送人员为空")
var tasks []types.TrainingPushTask
require.NoError(t, svc.db.Where("tenant_id = ?", tenantID).Find(&tasks).Error)
require.Len(t, tasks, 1, "校验失败不应落任务")
}
// 定时推送全链路:创建落 pending(不产生通知行)→ 调度器到期认领扇出并置
// sent → 重复执行靠唯一索引幂等不重发。
func TestCreateManualPushScheduledAndDispatch(t *testing.T) {
svc, sched, _, tenantID := newManualPushFixture(t)
seedManualPushOrg(t, svc.db, tenantID)
ctx := context.Background()
upcoming := time.Now().Add(time.Hour)
result, err := svc.CreateManualPush(ctx, tenantID, "op-1", &types.TrainingManualPushRequest{
SendAt: &upcoming,
})
require.NoError(t, err)
require.True(t, result.Scheduled)
require.Equal(t, types.PushTaskStatusPending, result.Task.Status)
var rows []types.TrainingNotification
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Empty(t, rows, "定时未到不应产生通知行")
// 把 send_at 拨到过去模拟到期 → 调度器认领扇出
require.NoError(t, svc.db.Model(&types.TrainingPushTask{}).
Where("tenant_id = ? AND status = ?", tenantID, types.PushTaskStatusPending).
Update("send_at", time.Now().Add(-time.Minute)).Error)
require.NoError(t, sched.dispatchManualPushTasks(ctx))
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Len(t, rows, 4, "全员 4 人各一条站内通知")
var task types.TrainingPushTask
require.NoError(t, svc.db.Where("tenant_id = ? AND status = ?", tenantID, types.PushTaskStatusSent).First(&task).Error)
require.Equal(t, 4, task.SentCount)
// 再跑一轮:任务已 sent 不再认领,通知行不翻倍
require.NoError(t, sched.dispatchManualPushTasks(ctx))
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Len(t, rows, 4, "重试只补漏不重发(唯一索引幂等)")
}
// 取消:pending 可取消;sent/已取消不可再取消;取消后的任务不被调度器投递。
func TestManualPushCancelLifecycle(t *testing.T) {
svc, sched, _, tenantID := newManualPushFixture(t)
seedManualPushOrg(t, svc.db, tenantID)
ctx := context.Background()
upcoming := time.Now().Add(time.Hour)
result, err := svc.CreateManualPush(ctx, tenantID, "op-1", &types.TrainingManualPushRequest{SendAt: &upcoming})
require.NoError(t, err)
require.NoError(t, svc.CancelManualPushTask(ctx, tenantID, result.Task.ID))
var task types.TrainingPushTask
require.NoError(t, svc.db.Where("id = ?", result.Task.ID).First(&task).Error)
require.Equal(t, types.PushTaskStatusCancelled, task.Status)
require.Error(t, svc.CancelManualPushTask(ctx, tenantID, result.Task.ID), "已取消不可重复取消")
require.Error(t, svc.CancelManualPushTask(ctx, tenantID, "missing-id"), "不存在的任务报错")
// 调度器只认领 pending:取消任务不投递
require.NoError(t, sched.dispatchManualPushTasks(ctx))
var rows []types.TrainingNotification
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Empty(t, rows)
// 列表只剩 pending(空),人员范围摘要正确
tasks, err := svc.ListManualPushTasks(ctx, tenantID)
require.NoError(t, err)
require.Empty(t, tasks)
_, err = svc.CreateManualPush(ctx, tenantID, "op-2", &types.TrainingManualPushRequest{
AudienceMode: types.PushTaskAudienceDept, DeptIDs: []string{"d-1"}, SendAt: &upcoming,
})
require.NoError(t, err)
tasks, err = svc.ListManualPushTasks(ctx, tenantID)
require.NoError(t, err)
require.Len(t, tasks, 1)
require.Contains(t, tasks[0].AudienceText, "按部门", "人员范围摘要应可读")
require.Equal(t, "op-2", tasks[0].CreatedBy)
}
// 推送开关关闭(notify_push_enabled=false):站内通知照发,企微外箱不入
// (push_status 空),推送记录口径「仅站内」。
func TestManualPushDisabledInSiteOnly(t *testing.T) {
svc, _, _, tenantID := newManualPushFixture(t)
seedManualPushOrg(t, svc.db, tenantID)
ctx := context.Background()
require.NoError(t, svc.db.Create(&types.TrainingRuleConfig{
ID: trainingNewID(), TenantID: tenantID, RuleKey: "notify_push_enabled", RuleValue: types.JSON([]byte("false")),
}).Error)
result, err := svc.CreateManualPush(ctx, tenantID, "op-1", &types.TrainingManualPushRequest{})
require.NoError(t, err)
require.Equal(t, 4, result.AudienceCount)
var rows []types.TrainingNotification
require.NoError(t, svc.db.Where("tenant_id = ? AND scene = ?", tenantID, types.SceneManualPush).Find(&rows).Error)
require.Len(t, rows, 4)
for _, row := range rows {
require.Empty(t, row.PushStatus, "推送关闭时仅站内")
}
}
// 企微投递正文:manual_push 标题加粗置顶 + 正文,带落地页拼「点击查看」链接。
func TestWecomDispatchContentManualPush(t *testing.T) {
row := &claimedNotification{
Scene: types.SceneManualPush,
Title: "和信智汇学院",
Content: "重要通知",
LinkURL: "https://kbt.example.com",
}
require.Equal(t,
"**【和信智汇学院】**\n重要通知\n\n[点击查看>>](https://kbt.example.com)",
wecomDispatchContent(row))
row.LinkURL = ""
require.Equal(t, "**【和信智汇学院】**\n重要通知", wecomDispatchContent(row),
"无落地页时不拼链接行")
row.Title = ""
require.Equal(t, "重要通知", wecomDispatchContent(row), "空标题不输出空标题行")
}
@@ -600,6 +600,8 @@ const demandCollectPlanPath = "/platform/training/plan"
// wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。 // wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。
// 000165 复测:学员开课通知(session_notice_student)与开课提醒统一为 markdown // 000165 复测:学员开课通知(session_notice_student)与开课提醒统一为 markdown
// 样式 —— 站内标题加粗置顶(如【培训开课通知】),正文随配置模板。 // 样式 —— 站内标题加粗置顶(如【培训开课通知】),正文随配置模板。
// manual_push 手动推送同样标题加粗置顶,行内 link_url 非空时尾部拼
// 「点击查看>>」落地页链接(链接是增强,空 = 不拼)。
// demand_collect 且行内带 link_url 时追加两行 markdown 链接: // demand_collect 且行内带 link_url 时追加两行 markdown 链接:
// //
// 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略) // 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略)
@@ -615,6 +617,19 @@ func wecomDispatchContent(row *claimedNotification) string {
b.WriteString(strings.TrimSpace(row.Content)) b.WriteString(strings.TrimSpace(row.Content))
return b.String() return b.String()
} }
// manual_push 手动推送([2026-11 需求]):标题加粗置顶 + 正文,带落地页时
// 追加「点击查看」链接(未登录打开登录页,已登录进系统首页)。
if row.Scene == types.SceneManualPush {
var b strings.Builder
if title := strings.TrimSpace(row.Title); title != "" {
b.WriteString("**【" + title + "】**\n")
}
b.WriteString(strings.TrimSpace(row.Content))
if link := strings.TrimSpace(row.LinkURL); link != "" {
b.WriteString("\n\n[点击查看>>](" + link + ")")
}
return b.String()
}
if row.Scene != types.SceneDemandCollect || row.LinkURL == "" { if row.Scene != types.SceneDemandCollect || row.LinkURL == "" {
return row.Content return row.Content
} }
@@ -194,6 +194,10 @@ func (s *TrainingScheduler) tick(ctx context.Context) {
if err := s.generateWeeklyLecturerReminders(ctx); err != nil { if err := s.generateWeeklyLecturerReminders(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] weekly lecturer reminders: %v", err) logger.Warnf(ctx, "[TrainingScheduler] weekly lecturer reminders: %v", err)
} }
// [2026-11 需求] 手动推送定时任务到期扇出(立即推送在接口内同步扇出)。
if err := s.dispatchManualPushTasks(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] manual push tasks: %v", err)
}
if err := s.dispatchPending(ctx); err != nil { if err := s.dispatchPending(ctx); err != nil {
logger.Warnf(ctx, "[TrainingScheduler] dispatch pending: %v", err) logger.Warnf(ctx, "[TrainingScheduler] dispatch pending: %v", err)
} }
@@ -873,3 +873,71 @@ func (h *Handler) ListPushLogs(c *gin.Context) {
} }
c.JSON(http.StatusOK, gin.H{"success": true, "data": page}) c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
} }
// CreateManualPush POST /training/notifications/manual-push — 配置中心「手动推送」
// (人事/课长;超管旁路见 requireRoles):标题/内容/落地页 + 人员范围(全员/
// 按部门/按职位/按人员)+ 立即(send_at 空)或定时(send_at RFC3339/北京时间)。
// 立即推送同步扇出站内+企微外箱;定时任务落 tr_push_tasks 由调度器到期投递。
func (h *Handler) CreateManualPush(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
Title string `json:"title"`
Content string `json:"content"`
LinkURL string `json:"link_url"`
AudienceMode string `json:"audience_mode"`
DeptIDs []string `json:"dept_ids"`
Posts []string `json:"posts"`
UserIDs []string `json:"user_ids"`
SendAt string `json:"send_at"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
result, err := h.svc.CreateManualPush(ctx, callerTenantID(c), callerUserID(c),
&types.TrainingManualPushRequest{
Title: req.Title,
Content: req.Content,
LinkURL: req.LinkURL,
AudienceMode: req.AudienceMode,
DeptIDs: req.DeptIDs,
Posts: req.Posts,
UserIDs: req.UserIDs,
SendAt: parseFlexibleTime(req.SendAt),
})
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
// ListManualPushTasks GET /training/notifications/manual-push-tasks — 待发送
// 定时任务列表(配置中心「手动推送」面板展示,含人员范围摘要/创建人姓名)。
func (h *Handler) ListManualPushTasks(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
items, err := h.svc.ListManualPushTasks(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// CancelManualPushTask POST /training/notifications/manual-push-tasks/:id/cancel
// — 取消待发送定时任务(仅 pending 可取消,已认领/已发送报错由前端提示刷新)。
func (h *Handler) CancelManualPushTask(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
if err := h.svc.CancelManualPushTask(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+7
View File
@@ -225,6 +225,13 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
trainingGroup.POST("/notifications/run-weekly", g.Contributor(), h.RunWeeklyLecturerReminders) trainingGroup.POST("/notifications/run-weekly", g.Contributor(), h.RunWeeklyLecturerReminders)
// notifications/push-logs 推送逐人明细(HR/课长,配置中心"推送记录")。 // notifications/push-logs 推送逐人明细(HR/课长,配置中心"推送记录")。
trainingGroup.GET("/notifications/push-logs", g.Contributor(), h.ListPushLogs) trainingGroup.GET("/notifications/push-logs", g.Contributor(), h.ListPushLogs)
// ---- 手动推送([2026-11 需求] 配置中心 · 推送管理) ----
// notifications/manual-push 手动推送一次通知(标题/内容/落地页 + 全员/
// 部门/职位/指定人员 + 立即/定时;HR/课长,角色细控在 handler 内)。
trainingGroup.POST("/notifications/manual-push", g.Contributor(), h.CreateManualPush)
// notifications/manual-push-tasks 待发送定时任务列表与取消(HR/课长)。
trainingGroup.GET("/notifications/manual-push-tasks", g.Contributor(), h.ListManualPushTasks)
trainingGroup.POST("/notifications/manual-push-tasks/:id/cancel", g.Contributor(), h.CancelManualPushTask)
// ---- 讲师结算 ---- // ---- 讲师结算 ----
trainingGroup.POST("/lecturer-scores/settle", g.Contributor(), h.SettleLecturerScores) trainingGroup.POST("/lecturer-scores/settle", g.Contributor(), h.SettleLecturerScores)
+31
View File
@@ -299,6 +299,28 @@ type TrainingRepository interface {
// ListMembersByUserIDs 按平台用户 ID 集合取员工档案(联 users 取展示姓名)。 // ListMembersByUserIDs 按平台用户 ID 集合取员工档案(联 users 取展示姓名)。
ListMembersByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingMember, error) ListMembersByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingMember, error)
// ---- 手动推送(配置中心 · 推送管理,[2026-11 需求]) ----
// CreatePushTask 落一条推送意图(立即/定时共用)。
CreatePushTask(ctx context.Context, task *types.TrainingPushTask) error
// GetPushTask 取单条任务(取消/重试前校验)。
GetPushTask(ctx context.Context, tenantID uint64, id string) (*types.TrainingPushTask, error)
// ListPushTasksByStatus 按状态取任务列表(待发送定时任务展示)。
ListPushTasksByStatus(ctx context.Context, tenantID uint64, status string, limit int) ([]*types.TrainingPushTask, error)
// ClaimDuePushTasks 扫描到期任务并逐条 CAS 认领(pending→sending,
// 多实例安全;SQLite 兼容,不用 SKIP LOCKED)。
ClaimDuePushTasks(ctx context.Context, now time.Time, limit int) ([]*types.TrainingPushTask, error)
// MarkPushTaskSent 记录扇出完成(仅 sending 态可落,防并发重复)。
MarkPushTaskSent(ctx context.Context, id string, sentCount int, sentAt time.Time) error
// RequeueStalePushTasks sending 超时(实例崩溃)回 pending 重投。
RequeueStalePushTasks(ctx context.Context, staleBefore time.Time) (int64, error)
// RequeuePushTask 单条 sending 任务回 pending(扇出瞬时失败重试)。
RequeuePushTask(ctx context.Context, id string) error
// CancelPushTask 取消待发送任务(CAS 仅 pending 可取消)。
CancelPushTask(ctx context.Context, tenantID uint64, id string) (bool, error)
// ListManualPushAudience 解析手动推送人员名单(user_id 去重):
// all=空间全部 active 成员 / dept=部门员工 / post=职位员工 / user=指定人员。
ListManualPushAudience(ctx context.Context, tenantID uint64, mode string, deptIDs, posts, userIDs []string) ([]string, error)
// ---- 看板聚合 ---- // ---- 看板聚合 ----
MonthCompletion(ctx context.Context, tenantID uint64, year, month int) (*types.TrainingMonthCompletion, error) MonthCompletion(ctx context.Context, tenantID uint64, year, month int) (*types.TrainingMonthCompletion, error)
DeptCompletionRanking(ctx context.Context, tenantID uint64, year int) ([]*types.TrainingDeptProgress, error) DeptCompletionRanking(ctx context.Context, tenantID uint64, year int) ([]*types.TrainingDeptProgress, error)
@@ -569,6 +591,15 @@ type TrainingService interface {
// ListPushLogs 管理端逐人推送明细(收件人姓名/工号已映射),供配置中心 // ListPushLogs 管理端逐人推送明细(收件人姓名/工号已映射),供配置中心
// 展示;返回当前页行、命中总数与全量状态统计(统计不受分页影响)。 // 展示;返回当前页行、命中总数与全量状态统计(统计不受分页影响)。
ListPushLogs(ctx context.Context, tenantID uint64, q *types.TrainingPushLogQuery) (*types.TrainingPushLogPage, error) ListPushLogs(ctx context.Context, tenantID uint64, q *types.TrainingPushLogQuery) (*types.TrainingPushLogPage, error)
// ---- 手动推送([2026-11 需求] 配置中心 · 推送管理) ----
// CreateManualPush 创建一次手动推送(标题/内容/落地页 + 人员范围 +
// 立即/定时):立即同步扇出并置 sent,定时落 pending 任务由调度器投递。
CreateManualPush(ctx context.Context, tenantID uint64, operatorID string, req *types.TrainingManualPushRequest) (*types.TrainingManualPushResult, error)
// ListManualPushTasks 待发送定时任务列表(附人员范围摘要/创建人姓名)。
ListManualPushTasks(ctx context.Context, tenantID uint64) ([]*types.TrainingPushTaskItem, error)
// CancelManualPushTask 取消待发送任务(仅 pending 可取消)。
CancelManualPushTask(ctx context.Context, tenantID uint64, id string) error
} }
// TrainingNotificationPusher exposes the WeCom push plumbing for operator // TrainingNotificationPusher exposes the WeCom push plumbing for operator
+92
View File
@@ -1419,6 +1419,12 @@ const (
// RefTypePlan marks notifications whose ref_id is a plan year (e.g. 2027); // RefTypePlan marks notifications whose ref_id is a plan year (e.g. 2027);
// 前端铃铛点击 ref_type=plan 跳转年培训计划页。 // 前端铃铛点击 ref_type=plan 跳转年培训计划页。
RefTypePlan = "plan" RefTypePlan = "plan"
// SceneManualPush 手动推送(配置中心 · 推送管理):标题/内容/落地页可自定义,
// 通知行 ref_type=manual_push、ref_id=tr_push_tasks.id,同一任务重试幂等。
SceneManualPush = "manual_push"
// RefTypeManualPush marks notifications whose ref_id is a tr_push_tasks.id
// (手动推送任务);站内铃铛点击 ref_type=manual_push 打开通知行 link_url 落地页。
RefTypeManualPush = "manual_push"
) )
// TrainingRemindScene builds the scene key of a T-N days session reminder. // TrainingRemindScene builds the scene key of a T-N days session reminder.
@@ -1523,6 +1529,92 @@ type TrainingPushLog struct {
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
// ---------------------------------------------------------------------------
// 手动推送(配置中心 · 推送管理,[2026-11 需求])
// ---------------------------------------------------------------------------
// 手动推送任务状态(tr_push_tasks.status):pending 待发送(定时未到)/sending
// 调度器已认领/sent 已完成入箱/cancelled 已取消。
const (
PushTaskStatusPending = "pending"
PushTaskStatusSending = "sending"
PushTaskStatusSent = "sent"
PushTaskStatusCancelled = "cancelled"
)
// 手动推送人员范围(tr_push_tasks.audience_mode):all 全员 / dept 按部门 /
// post 按职位 / user 指定人员。
const (
PushTaskAudienceAll = "all"
PushTaskAudienceDept = "dept"
PushTaskAudiencePost = "post"
PushTaskAudienceUser = "user"
)
// TrainingPushTask 手动推送任务(配置中心一次推送意图一行):标题/内容/落地页
// 自定义,人员范围按 mode 选一;定时任务由 training scheduler 在 send_at 到期
// 后按发送时点人员名单扇出到 tr_notifications(scene=manual_push)。
type TrainingPushTask struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Title string `json:"title" gorm:"type:varchar(255);default:''"`
Content string `json:"content" gorm:"type:text;default:''"`
// LinkURL 落地页地址(默认站点根路径:未登录=登录页,已登录=系统首页);
// 空 = 企微消息不带「点击查看」链接。
LinkURL string `json:"link_url" gorm:"type:varchar(512);default:''"`
AudienceMode string `json:"audience_mode" gorm:"type:varchar(16);default:'all'"`
DeptIDs JSON `json:"dept_ids" gorm:"type:jsonb;default:'[]'"`
Posts JSON `json:"posts" gorm:"type:jsonb;default:'[]'"`
UserIDs JSON `json:"user_ids" gorm:"type:jsonb;default:'[]'"`
SendAt time.Time `json:"send_at"`
Status string `json:"status" gorm:"type:varchar(16);default:'pending'"`
SentCount int `json:"sent_count" gorm:"default:0"`
SentAt *time.Time `json:"sent_at"`
CreatedBy string `json:"created_by" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
}
// TableName pins the physical table name.
func (TrainingPushTask) TableName() string { return "tr_push_tasks" }
// TrainingPushTaskItem 手动推送任务列表行(配置中心「待发送定时任务」):
// 附人员范围摘要文案与创建人姓名。
type TrainingPushTaskItem struct {
ID string `json:"id"`
Title string `json:"title"`
AudienceMode string `json:"audience_mode"`
AudienceText string `json:"audience_text"`
SendAt time.Time `json:"send_at"`
Status string `json:"status"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
SentAt *time.Time `json:"sent_at"`
SentCount int `json:"sent_count"`
}
// TrainingManualPushRequest 手动推送请求(配置中心「新建推送」弹窗):
// SendAt 为空 = 立即推送;否则为北京时间/ISO 定时发送时间。
type TrainingManualPushRequest struct {
Title string `json:"title"`
Content string `json:"content"`
LinkURL string `json:"link_url"`
AudienceMode string `json:"audience_mode"`
DeptIDs []string `json:"dept_ids"`
Posts []string `json:"posts"`
UserIDs []string `json:"user_ids"`
SendAt *time.Time `json:"send_at"`
}
// TrainingManualPushResult 手动推送创建结果:任务行 + 创建时点人员数预估
// (定时任务发送时按当时代名单重新解析)+ 是否定时。
type TrainingManualPushResult struct {
Task *TrainingPushTaskItem `json:"task"`
AudienceCount int `json:"audience_count"`
Scheduled bool `json:"scheduled"`
}
// TrainingSignSummary 场次签到统计(原型:应到/已到/迟到/异常待复核)。 // TrainingSignSummary 场次签到统计(原型:应到/已到/迟到/异常待复核)。
type TrainingSignSummary struct { type TrainingSignSummary struct {
SessionID string `json:"session_id"` SessionID string `json:"session_id"`
@@ -0,0 +1,4 @@
-- Migration: 000166_training_manual_push (down)
DO $$ BEGIN RAISE NOTICE '[Migration 000166] Dropping tr_push_tasks...'; END $$;
DROP TABLE IF EXISTS tr_push_tasks;
@@ -0,0 +1,43 @@
-- Migration: 000166_training_manual_push
-- Manual push (手动推送) from the config center push-management tab
-- (2026-11 requirement: 和信智汇学院重要通知随时手动推送).
-- tr_push_tasks stores one push intent per row: custom title/content/landing
-- link, an audience selector (all / by dept / by post / explicit users) and a
-- send time (now or scheduled). The training scheduler claims due rows with a
-- compare-and-set (pending → sending → sent), resolves the audience at send
-- time (so "全员" covers accounts created after scheduling) and fans the task
-- out into tr_notifications rows (scene='manual_push', ref_id=task id) that
-- flow through the existing WeCom outbox and 推送记录 views. Cancelled tasks
-- never fan out.
DO $$ BEGIN RAISE NOTICE '[Migration 000166] Creating tr_push_tasks for manual push...'; END $$;
CREATE TABLE IF NOT EXISTS tr_push_tasks (
id VARCHAR(36) PRIMARY KEY,
tenant_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
link_url VARCHAR(512) NOT NULL DEFAULT '',
audience_mode VARCHAR(16) NOT NULL DEFAULT 'all',
dept_ids JSONB NOT NULL DEFAULT '[]',
posts JSONB NOT NULL DEFAULT '[]',
user_ids JSONB NOT NULL DEFAULT '[]',
send_at TIMESTAMPTZ NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'pending',
sent_count INT NOT NULL DEFAULT 0,
sent_at TIMESTAMPTZ,
created_by VARCHAR(36) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_tr_push_tasks_tenant ON tr_push_tasks(tenant_id);
-- Due-task scan of the training scheduler tick (partial: pending rows only).
CREATE INDEX IF NOT EXISTS idx_tr_push_tasks_due
ON tr_push_tasks(send_at)
WHERE status = 'pending' AND deleted_at IS NULL;
COMMENT ON TABLE tr_push_tasks IS 'Manual push tasks (config center push management); scheduler fans due tasks out into tr_notifications';
COMMENT ON COLUMN tr_push_tasks.audience_mode IS 'Audience selector: all / dept / post / user';
COMMENT ON COLUMN tr_push_tasks.status IS 'pending (waiting or due) / sending (claimed) / sent / cancelled';