feat(training): 企业培训迭代:推送深链接与签名下载、课程管理修复与收集模板调整
推送域(000155):
- 广播通知支持 link_url:demand_collect 场景自动签发教育训练需求表模板
匿名下载直链(HMAC token,20 天有效,免登录路由),企微消息尾部拼
「下载模板 + 查看更多详情」链接;站内文本保持纯文本不受影响
- 配置中心新增「推送链接基址」(notify_link_base_url,多入口/内外网部署固定
权威地址,留空跟随推送人访问地址)与「年培训计划收集推送文案」
(demand_collect_*,{year} 渲染收集年度);空标题/内容按模板回落渲染
- 迁移 000155:tr_training_notifications 增 link_url/link_token 列
课程管理:
- 修复点【发布/下线】报「不支持的操作」:动作取值兼容字面量路由(FullPath
末段)与 :action 通配两种注册形态
- 列表新增「创建人」列:creator_id 联查 users 带出姓名,导出 Excel 同步;
新增课程「所属部门」默认当前登录用户所在部门
- 导入加固:表头归一化 + 别名模糊匹配(兼容内置模板/旧口径/自定义模板变体);
导入与新增行支持按部门名兜底解析为 id(前端名册未命中时传 owner_dept_name)
年培训计划:
- 需求列表新增「创建人/创建时间」列(submitter_id 联查 users 带出姓名)
- 收集模板调整:下载时动态删除「培训费用(RMB)」列(旧版自定义模板同步归一,
右侧列/合并/下拉随删列平移);备注右侧追加「调研维度/培训策划要求」说明列
(合并至数据区末行,自动换行带边框,已带说明的自定义模板不覆盖)
开发工具:
- air 热重载适配 Windows:构建收敛到 scripts/air_build.sh(规避 air 经
PowerShell 执行不支持 bash 命令替换),产物改 .exe 后缀;CGO_CFLAGS 取
持久化值并集追加,不覆盖 go env -w 的头文件包含路径
This commit is contained in:
1 parent
242dd7e1a6
commit
4e25fce9aa
30 files changed
+1150
-143
No files matched your search
@@ -39,10 +39,12 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
}
|
||||
var items []*types.TrainingCourseLibrary
|
||||
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
// owner_dept_name 联查部门名(所属部门存 org_depts id);
|
||||
// creator_name 联查创建人姓名(display_name 优先,回退 username 工号)。
|
||||
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
|
||||
Order("tr_course_library.updated_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&items).Error
|
||||
@@ -53,9 +55,10 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
|
||||
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
|
||||
var item types.TrainingCourseLibrary
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
|
||||
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name, COALESCE(NULLIF(cu.display_name, ''), cu.username, '') AS creator_name").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
|
||||
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users cu ON cu.id = tr_course_library.creator_id").
|
||||
Where("tr_course_library.tenant_id = ? AND tr_course_library.id = ?", tenantID, id).First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -58,11 +58,13 @@ func (r *trainingRepository) ListDemands(ctx context.Context, tenantID uint64, q
|
||||
}
|
||||
var items []*types.TrainingDemand
|
||||
// lecturer_name 同口径取真实姓名(display_name 优先,回退 username 工号;
|
||||
// lecturer_id 为空或用户已删时回退外部讲师姓名 lecturer_external)。
|
||||
// lecturer_id 为空或用户已删时回退外部讲师姓名 lecturer_external);
|
||||
// submitter_name 联查提报人姓名(年培训计划「创建人」列)。
|
||||
err := filter().
|
||||
Select("tr_demands.*, COALESCE(dp.name, '') AS dept_name, COALESCE(NULLIF(lu.display_name, ''), lu.username, tr_demands.lecturer_external, '') AS lecturer_name").
|
||||
Select("tr_demands.*, COALESCE(dp.name, '') AS dept_name, COALESCE(NULLIF(lu.display_name, ''), lu.username, tr_demands.lecturer_external, '') AS lecturer_name, COALESCE(NULLIF(su.display_name, ''), su.username, '') AS submitter_name").
|
||||
Joins("LEFT JOIN org_depts dp ON dp.id = tr_demands.dept_id AND dp.tenant_id = tr_demands.tenant_id AND dp.deleted_at IS NULL").
|
||||
Joins("LEFT JOIN users lu ON lu.id = tr_demands.lecturer_id").
|
||||
Joins("LEFT JOIN users su ON su.id = tr_demands.submitter_id").
|
||||
Order("tr_demands.created_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&items).Error
|
||||
|
||||
@@ -687,15 +687,15 @@ func (s *trainingService) RollMonthPlans(ctx context.Context, tenantID uint64, f
|
||||
}
|
||||
}
|
||||
plan := &types.TrainingMonthPlan{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
Year: nextYear,
|
||||
Month: nextMonth,
|
||||
Title: courseName,
|
||||
Status: types.TrainingMonthPlanDraft,
|
||||
RollFromID: session.ID,
|
||||
RollTimes: rollTimes,
|
||||
Escalated: rollTimes >= 2, // 连续两月未完成升级并抄送人事
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
Year: nextYear,
|
||||
Month: nextMonth,
|
||||
Title: courseName,
|
||||
Status: types.TrainingMonthPlanDraft,
|
||||
RollFromID: session.ID,
|
||||
RollTimes: rollTimes,
|
||||
Escalated: rollTimes >= 2, // 连续两月未完成升级并抄送人事
|
||||
SubmitterID: operatorID,
|
||||
}
|
||||
if err := s.repo.CreateMonthPlan(ctx, plan); err != nil {
|
||||
|
||||
@@ -2,11 +2,14 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
@@ -46,11 +49,11 @@ func TestBroadcastNotificationRepeatsDeliver(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
users := []string{"u-1", "u-2", "u-3", "u-4"}
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(users), sent)
|
||||
|
||||
sent2, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027")
|
||||
sent2, err := svc.BroadcastNotification(ctx, tenantID, users, "demand_collect", "【培训需求收集】2027年度培训计划收集", "content", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(users), sent2)
|
||||
|
||||
@@ -70,7 +73,7 @@ func TestBroadcastNotificationPushToggle(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
@@ -83,7 +86,7 @@ func TestBroadcastNotificationPushToggle(t *testing.T) {
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID, RuleKey: "notify_push_enabled", RuleValue: types.JSON([]byte("false")),
|
||||
}).Error)
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows = countBroadcastRows(t, db, tenantID)
|
||||
@@ -98,14 +101,153 @@ func TestBroadcastNotificationValidation(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.BroadcastNotification(ctx, tenantID, nil, "demand_collect", "t", "c", "plan", "2027")
|
||||
_, err := svc.BroadcastNotification(ctx, tenantID, nil, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "请选择推送人员")
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"", "u-1", ""}, "demand_collect", "t", "c", "plan", "2027")
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"", "u-1", ""}, "demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, "u-1", rows[0].TargetUserID, "空串 user_id 应被跳过,只落有效收件人")
|
||||
}
|
||||
|
||||
// [2026-11 需求] demand_collect 广播带 link_url:归一化尾部斜杠落库,并为
|
||||
// 教育训练需求表模板签发可校验的匿名下载 token;其他场景/非法地址一律空,
|
||||
// 链接是增强不是前提(核验/确认等站内广播不受影响)。
|
||||
func TestBroadcastNotificationDeepLink(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1", "u-2"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "https://aido.example.com/")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, sent)
|
||||
rows := countBroadcastRows(t, db, tenantID)
|
||||
require.Len(t, rows, 2)
|
||||
for _, row := range rows {
|
||||
require.Equal(t, "https://aido.example.com", row.LinkURL, "尾部斜杠应归一化")
|
||||
require.NotEmpty(t, row.LinkToken)
|
||||
payload, err := utils.VerifyTrainingTemplateToken(row.LinkToken)
|
||||
require.NoError(t, err, "落库 token 必须可回验")
|
||||
require.Equal(t, tenantID, payload.TenantID)
|
||||
require.Equal(t, types.TrainingTemplateDemandCollection, payload.TemplateKey)
|
||||
}
|
||||
|
||||
// 同一批广播共享同一 token(一次签名,整批复用)
|
||||
require.Equal(t, rows[0].LinkToken, rows[1].LinkToken)
|
||||
|
||||
// 非 demand_collect 场景:带 link_url 也不落链接
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_verify", "t", "c", "plan", "2027", "https://aido.example.com")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
var verifyRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&verifyRow).Error)
|
||||
require.Empty(t, verifyRow.LinkURL)
|
||||
require.Empty(t, verifyRow.LinkToken)
|
||||
|
||||
// 非法地址(非 http(s) 绝对地址)与空地址:不落链接
|
||||
for _, bad := range []string{"", "javascript:alert(1)", "/platform/training/plan"} {
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-4"},
|
||||
"demand_collect", "t", "c", "plan", "2027", bad)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
var plainRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-4").
|
||||
Order("created_at DESC").First(&plainRow).Error)
|
||||
require.Empty(t, plainRow.LinkURL)
|
||||
require.Empty(t, plainRow.LinkToken)
|
||||
}
|
||||
|
||||
// [2026-11 需求] 环境级基址覆盖:配置中心 notify_link_base_url 优先于推送人
|
||||
// 浏览器 origin —— 多入口/内外网部署时链接固定指向权威域名,本地开发不配置
|
||||
// 则回落 origin;覆盖值非法时回落 origin,再非法则不落链接。
|
||||
func TestBroadcastNotificationLinkBaseOverride(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
RuleKey: "notify_link_base_url", RuleValue: types.JSON([]byte(`"https://aido.corp.com"`)),
|
||||
}).Error)
|
||||
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "http://localhost:5173")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
var row types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-1").First(&row).Error)
|
||||
require.Equal(t, "https://aido.corp.com", row.LinkURL, "环境覆盖应优先于推送 origin")
|
||||
require.NotEmpty(t, row.LinkToken)
|
||||
|
||||
// 覆盖值非法(非 http(s))→ 回落推送 origin
|
||||
require.NoError(t, db.Model(&types.TrainingRuleConfig{}).
|
||||
Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_link_base_url").
|
||||
Update("rule_value", types.JSON([]byte(`"not-a-url"`))).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "http://localhost:5173")
|
||||
require.NoError(t, err)
|
||||
var fallbackRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-2").First(&fallbackRow).Error)
|
||||
require.Equal(t, "http://localhost:5173", fallbackRow.LinkURL)
|
||||
|
||||
// 覆盖与 origin 均空/非法 → 不落链接
|
||||
require.NoError(t, db.Model(&types.TrainingRuleConfig{}).
|
||||
Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_link_base_url").
|
||||
Update("rule_value", types.JSON([]byte(`""`))).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_collect", "t", "c", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
var emptyRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&emptyRow).Error)
|
||||
require.Empty(t, emptyRow.LinkURL)
|
||||
}
|
||||
|
||||
// [2026-11 需求] 年培训计划收集推送文案可配(notify_text_templates
|
||||
// demand_collect_*):广播空标题/内容按模板回落渲染,{year} 以 ref_id
|
||||
// 收集年度替换;调用方显式传入的文案不被覆盖;字段清空回落内置默认。
|
||||
func TestBroadcastNotificationDemandCollectTextTemplates(t *testing.T) {
|
||||
svc, db, tenantID := newBroadcastFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 配置中心自定义收集文案
|
||||
require.NoError(t, db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
RuleKey: "notify_text_templates",
|
||||
RuleValue: types.JSON([]byte(`{"demand_collect_title":"【年度计划】{year}年需求提报",
|
||||
"demand_collect_content":"请于 {year} 年提报年度培训需求。","weekly_title":""}`)),
|
||||
}).Error)
|
||||
|
||||
// 空标题/内容 → 模板渲染;显式传入 → 原样保留
|
||||
sent, err := svc.BroadcastNotification(ctx, tenantID, []string{"u-1"},
|
||||
"demand_collect", "", "", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
sent, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-2"},
|
||||
"demand_collect", "手写标题", "手写内容", "plan", "2027", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, sent)
|
||||
|
||||
var tplRow, explicitRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-1").First(&tplRow).Error)
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-2").First(&explicitRow).Error)
|
||||
require.Equal(t, "【年度计划】2027年需求提报", tplRow.Title)
|
||||
require.Equal(t, "请于 2027 年提报年度培训需求。", tplRow.Content)
|
||||
require.Equal(t, "手写标题", explicitRow.Title)
|
||||
require.Equal(t, "手写内容", explicitRow.Content)
|
||||
|
||||
// 字段清空(回落内置默认)且 ref_id 不带年份前缀 → {year} 渲染为下一年
|
||||
require.NoError(t, db.Where("tenant_id = ? AND rule_key = ?", tenantID, "notify_text_templates").
|
||||
Delete(&types.TrainingRuleConfig{}).Error)
|
||||
_, err = svc.BroadcastNotification(ctx, tenantID, []string{"u-3"},
|
||||
"demand_collect", "", "", "plan", "", "")
|
||||
require.NoError(t, err)
|
||||
var fallbackRow types.TrainingNotification
|
||||
require.NoError(t, db.Where("tenant_id = ? AND target_user_id = ?", tenantID, "u-3").First(&fallbackRow).Error)
|
||||
nextYear := beijingNow(time.Now()).Year() + 1
|
||||
require.Equal(t, fmt.Sprintf("【培训需求收集】%d年度培训计划收集", nextYear), fallbackRow.Title)
|
||||
require.Contains(t, fallbackRow.Content,
|
||||
fmt.Sprintf("请各部门于 %d 年 1 月 31 日前提报 %d 年度培训需求", nextYear, nextYear))
|
||||
}
|
||||
@@ -12,12 +12,15 @@ import (
|
||||
"path"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"academy/internal/utils"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
@@ -1426,16 +1429,35 @@ func (s *trainingService) Notify(ctx context.Context, tenantID uint64, targetUse
|
||||
// 运营场景),站内 + 企微外箱(调度器 dispatchPending 消费)。手动广播是离散
|
||||
// 的发送动作:ref_id 追加发送时间戳,避免与唯一索引 (tenant,target,scene,ref)
|
||||
// 冲突把已收过通知的人静默去重;返回成功入箱条数。
|
||||
func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID string) (int, error) {
|
||||
// linkURL 为前端 origin(可空):demand_collect 场景据此生成教育训练需求表
|
||||
// 模板的匿名下载签名 token(20 天有效)随行落库,调度器投递企微时拼尾部
|
||||
// 「下载模板/查看详情」链接;站内 content 保持纯文本不受影响。
|
||||
// demand_collect 场景空标题/内容按配置中心文案模板回落渲染(见 training_notify.go)。
|
||||
func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID, linkURL string) (int, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return 0, errors.NewBadRequestError("请选择推送人员")
|
||||
}
|
||||
if scene == "" {
|
||||
scene = "demand_collect"
|
||||
scene = types.SceneDemandCollect
|
||||
}
|
||||
// [2026-11 需求] 年培训计划收集推送文案:配置中心「提醒推送文案」卡
|
||||
// (notify_text_templates demand_collect_*)可编辑;调用方未带标题/内容时
|
||||
// 按模板回落渲染,{year} 取 ref_id 收集年度(缺省北京时间下一年)。
|
||||
if scene == types.SceneDemandCollect {
|
||||
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
|
||||
year := strconv.Itoa(demandCollectYear(refID, time.Now()))
|
||||
vars := map[string]string{"year": year}
|
||||
if strings.TrimSpace(title) == "" {
|
||||
title = renderNotifyTemplate(tpl.DemandCollectTitle, vars)
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
content = renderNotifyTemplate(tpl.DemandCollectContent, vars)
|
||||
}
|
||||
}
|
||||
if refID != "" {
|
||||
refID = fmt.Sprintf("%s-%d", refID, time.Now().UnixNano())
|
||||
}
|
||||
linkURL, linkToken := s.broadcastDeepLink(ctx, tenantID, scene, linkURL)
|
||||
push := s.loadPushEnabled(ctx, tenantID)
|
||||
now := time.Now()
|
||||
status := ""
|
||||
@@ -1451,6 +1473,7 @@ func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID ui
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
TargetUserID: uid, Channel: "inapp", Scene: scene,
|
||||
Title: title, Content: content, RefType: refType, RefID: refID,
|
||||
LinkURL: linkURL, LinkToken: linkToken,
|
||||
SentAt: now, PushStatus: status,
|
||||
})
|
||||
}
|
||||
@@ -1463,6 +1486,60 @@ func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID ui
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// broadcastDeepLink 解析广播外链基址并为 demand_collect 场景签发模板匿名
|
||||
// 下载 token。基址取值优先级:配置中心 notify_link_base_url(环境级覆盖,
|
||||
// 多入口/内外网部署固定指向权威域名)> 前端推送 origin(window.location.origin,
|
||||
// 本地开发零配置可用)。仅接受 http(s) 绝对地址;非法或非收集场景一律退回
|
||||
// 空串,不阻断通知本身(链接是增强,不是前提)。
|
||||
func (s *trainingService) broadcastDeepLink(ctx context.Context, tenantID uint64, scene, linkURL string) (string, string) {
|
||||
if scene != types.SceneDemandCollect {
|
||||
return "", ""
|
||||
}
|
||||
linkURL = normalizeLinkBase(s.loadLinkBaseOverride(ctx, tenantID), linkURL)
|
||||
if linkURL == "" {
|
||||
return "", ""
|
||||
}
|
||||
token, err := utils.SignTrainingTemplateToken(&utils.TrainingTemplateTokenPayload{
|
||||
TenantID: tenantID,
|
||||
TemplateKey: types.TrainingTemplateDemandCollection,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingBroadcast] sign template download token: %v", err)
|
||||
return "", ""
|
||||
}
|
||||
return linkURL, token
|
||||
}
|
||||
|
||||
// loadLinkBaseOverride 读配置中心 notify_link_base_url(bare string;空 = 未配置)。
|
||||
func (s *trainingService) loadLinkBaseOverride(ctx context.Context, tenantID uint64) string {
|
||||
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if rule.RuleKey == ruleKeyNotifyLinkBaseURL {
|
||||
var v string
|
||||
if json.Unmarshal(rule.RuleValue, &v) == nil {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// normalizeLinkBase 从候选(优先配置覆盖,其次调用方 origin)选出一个合法的
|
||||
// http(s) 基址:去空白与尾部斜杠;候选均非法时返回空串。
|
||||
func normalizeLinkBase(override, origin string) string {
|
||||
for _, candidate := range []string{override, origin} {
|
||||
candidate = strings.TrimRight(strings.TrimSpace(candidate), "/")
|
||||
if strings.HasPrefix(candidate, "http://") || strings.HasPrefix(candidate, "https://") {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 小工具
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -67,6 +67,33 @@ func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID u
|
||||
return s.repo.ListCourseLibrary(ctx, tenantID, q)
|
||||
}
|
||||
|
||||
// resolveCourseLibraryDept 所属部门兜底解析:新增/导入行仅传部门名(owner_dept_name,
|
||||
// 前端部门名册未加载或模板列口径不一致时)按组织架构匹配为 id:名称精确 →
|
||||
// 行值包含部门名(与需求导入同口径)。解析失败保持原值(留空即列表「-」),不阻断导入。
|
||||
func (s *trainingService) resolveCourseLibraryDept(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary) {
|
||||
name := strings.TrimSpace(item.OwnerDeptName)
|
||||
if item.OwnerDeptID != "" || name == "" {
|
||||
return
|
||||
}
|
||||
depts, err := s.org.ListDepts(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Skip course library dept name resolve, tenant=%d dept=%s error: %v", tenantID, name, err)
|
||||
return
|
||||
}
|
||||
for _, d := range depts {
|
||||
if d.Name == name {
|
||||
item.OwnerDeptID = d.ID
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, d := range depts {
|
||||
if d.Name != "" && strings.Contains(name, d.Name) {
|
||||
item.OwnerDeptID = d.ID
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。
|
||||
func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) {
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
@@ -76,6 +103,8 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
|
||||
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
||||
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
|
||||
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
|
||||
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
|
||||
@@ -148,6 +177,8 @@ func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID
|
||||
if err := normalizeCourseLibrary(item); err != nil {
|
||||
continue // 缺课程名称的行跳过(前端同步提示跳过行数)
|
||||
}
|
||||
// 仅传部门名的行按组织架构解析为 id(前端匹配失败/未传 id 的兜底)。
|
||||
s.resolveCourseLibraryDept(ctx, tenantID, item)
|
||||
item.ID = trainingNewID()
|
||||
item.TenantID = tenantID
|
||||
item.CreatorID = updaterID
|
||||
@@ -190,7 +221,7 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
|
||||
// 列口径对齐《教育训练需求表》:所属部门=主办单位,适合人员=参加人员,
|
||||
// 课件=课件收集;导入解析端(LibraryPanel onImportExcel)两套列名均兼容。
|
||||
headers := []string{"课程编号", "所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
|
||||
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建时间"}
|
||||
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建人", "创建时间"}
|
||||
for i, h := range headers {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
|
||||
_ = f.SetCellValue(sheet, cell, h)
|
||||
@@ -208,7 +239,7 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
|
||||
}
|
||||
values := []string{item.Code, item.OwnerDeptName, item.Name, item.Description, item.SuitableMembers, item.Category,
|
||||
courseLibraryTypeLabel(item.Type), courseLibraryModeLabel(item.Mode),
|
||||
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatedAt.Format("2006-01-02 15:04")}
|
||||
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatorName, item.CreatedAt.Format("2006-01-02 15:04")}
|
||||
for i, v := range values {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, r+2)
|
||||
_ = f.SetCellValue(sheet, cell, v)
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// 周一讲师汇总提醒的规则键(ruleKeyNotifyWeeklyLecturer* 定义在
|
||||
@@ -121,6 +122,9 @@ type notifyTextTemplates struct {
|
||||
// 周一讲师未完成汇总提醒:标题与内容
|
||||
WeeklyTitle string `json:"weekly_title"`
|
||||
WeeklyContent string `json:"weekly_content"`
|
||||
// 年培训计划收集推送(scene=demand_collect):广播空标题/内容回落渲染
|
||||
DemandCollectTitle string `json:"demand_collect_title"`
|
||||
DemandCollectContent string `json:"demand_collect_content"`
|
||||
}
|
||||
|
||||
// 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。
|
||||
@@ -133,6 +137,9 @@ const (
|
||||
defaultLecturerMaintainFooter = "该课程尚未上传课件/学习材料,请尽快登录培训平台补齐,以免影响学员课前学习。"
|
||||
defaultWeeklyTitle = "{year}年{month}月教育训练(第{week}周提醒)"
|
||||
defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
|
||||
// 年培训计划收集推送默认文案(与前端收集弹窗历史硬编码逐字一致;{year} 渲染收集年度)
|
||||
defaultDemandCollectTitle = "【培训需求收集】{year}年度培训计划收集"
|
||||
defaultDemandCollectContent = "请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。"
|
||||
)
|
||||
|
||||
func defaultNotifyTextTemplates() notifyTextTemplates {
|
||||
@@ -145,6 +152,8 @@ func defaultNotifyTextTemplates() notifyTextTemplates {
|
||||
LecturerMaintainFooter: defaultLecturerMaintainFooter,
|
||||
WeeklyTitle: defaultWeeklyTitle,
|
||||
WeeklyContent: defaultWeeklyContent,
|
||||
DemandCollectTitle: defaultDemandCollectTitle,
|
||||
DemandCollectContent: defaultDemandCollectContent,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +178,8 @@ func parseNotifyTextTemplates(raw []byte) notifyTextTemplates {
|
||||
fill(&t.LecturerMaintainFooter, saved.LecturerMaintainFooter)
|
||||
fill(&t.WeeklyTitle, saved.WeeklyTitle)
|
||||
fill(&t.WeeklyContent, saved.WeeklyContent)
|
||||
fill(&t.DemandCollectTitle, saved.DemandCollectTitle)
|
||||
fill(&t.DemandCollectContent, saved.DemandCollectContent)
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -562,6 +573,53 @@ func (s *trainingService) RunWeeklyLecturerReminders(ctx context.Context, tenant
|
||||
return s.enqueueWeeklyLecturerReminders(ctx, tenantID, time.Now(), s.loadPushEnabled(ctx, tenantID))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// demand_collect 年培训计划收集推送(2026-11 需求:文案可配 + 模板下载/详情入口)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// demandCollectYear 从广播 ref_id 前缀解析收集年度("2027-<纳秒>" → 2027,
|
||||
// 前端收集弹窗恒传下一年度);无合法年份前缀时回退北京时间下一年。
|
||||
func demandCollectYear(refID string, now time.Time) int {
|
||||
if idx := strings.IndexByte(refID, '-'); idx > 0 {
|
||||
refID = refID[:idx]
|
||||
}
|
||||
if year, err := strconv.Atoi(refID); err == nil && year >= 2000 && year <= 2999 {
|
||||
return year
|
||||
}
|
||||
return beijingNow(now).Year() + 1
|
||||
}
|
||||
|
||||
// demandCollectPlanPath 年培训计划页(前端铃铛 ref_type=plan 同款跳转目标)。
|
||||
const demandCollectPlanPath = "/platform/training/plan"
|
||||
|
||||
// wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。
|
||||
// demand_collect 且行内带 link_url 时追加两行 markdown 链接:
|
||||
//
|
||||
// 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略)
|
||||
// 查看更多详情>>(进入企业培训系统年培训计划页)
|
||||
//
|
||||
// 其余场景原样返回(提醒类场景的 markdown 由生成侧 remindContent 拼好)。
|
||||
func wecomDispatchContent(row *claimedNotification) string {
|
||||
if row.Scene != types.SceneDemandCollect || row.LinkURL == "" {
|
||||
return row.Content
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(strings.TrimRight(row.Content, "\n"))
|
||||
if row.LinkToken != "" {
|
||||
b.WriteString("\n\n[下载教育训练需求表模板](")
|
||||
b.WriteString(row.LinkURL)
|
||||
b.WriteString(utils.TrainingTemplateSignedFilePath)
|
||||
b.WriteString("?token=")
|
||||
b.WriteString(row.LinkToken)
|
||||
b.WriteString(")")
|
||||
}
|
||||
b.WriteString("\n[查看更多详情>>](")
|
||||
b.WriteString(row.LinkURL)
|
||||
b.WriteString(demandCollectPlanPath)
|
||||
b.WriteString(")")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 推送记录(管理台逐人明细)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -4,6 +4,7 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -17,12 +18,23 @@ func TestParseNotifyTextTemplatesFallsBackToDefaults(t *testing.T) {
|
||||
raw, err := json.Marshal(map[string]any{
|
||||
"student_notice_title": "自定义开课标题",
|
||||
"student_notice_content": "",
|
||||
"demand_collect_content": "自定义收集内容 {year}",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
got := parseNotifyTextTemplates(raw)
|
||||
require.Equal(t, "自定义开课标题", got.StudentNoticeTitle)
|
||||
require.Equal(t, defaultStudentNoticeContent, got.StudentNoticeContent)
|
||||
require.Equal(t, defaultWeeklyTitle, got.WeeklyTitle)
|
||||
require.Equal(t, defaultDemandCollectTitle, got.DemandCollectTitle)
|
||||
require.Equal(t, "自定义收集内容 {year}", got.DemandCollectContent)
|
||||
}
|
||||
|
||||
func TestDemandCollectYear(t *testing.T) {
|
||||
// ref_id 前缀为收集年度(带时间戳后缀同样可解析),非法/缺失回退下一年
|
||||
require.Equal(t, 2027, demandCollectYear("2027-1770000000000000000", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("2027", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
require.Equal(t, 2027, demandCollectYear("not-a-year", time.Date(2026, 11, 19, 0, 0, 0, 0, beijingZone)))
|
||||
}
|
||||
|
||||
func TestRenderNotifyTemplate(t *testing.T) {
|
||||
|
||||
@@ -65,6 +65,10 @@ const (
|
||||
// ruleKeyNotifyTextTemplates [2026-11 需求] 提醒推送文案模板(配置中心可编辑,
|
||||
// 空字段回落 training_notify.go 的内置默认文案)。
|
||||
ruleKeyNotifyTextTemplates = "notify_text_templates"
|
||||
// ruleKeyNotifyLinkBaseURL [2026-11 需求] 企微消息内深链接的对外基址覆盖
|
||||
// (bare string,如 https://aido.example.com):多入口/内外网部署时固定链接
|
||||
// 指向权威域名,优先于推送人浏览器 origin;空 = 用推送人 origin。
|
||||
ruleKeyNotifyLinkBaseURL = "notify_link_base_url"
|
||||
)
|
||||
|
||||
// sendingReclaimAfter bounds how long a claimed row may stay 'sending'
|
||||
@@ -588,6 +592,8 @@ type claimedNotification struct {
|
||||
Scene string
|
||||
Title string
|
||||
Content string
|
||||
LinkURL string
|
||||
LinkToken string
|
||||
PushAttempts int
|
||||
}
|
||||
|
||||
@@ -604,7 +610,7 @@ func (s *TrainingScheduler) dispatchPending(ctx context.Context) error {
|
||||
FOR UPDATE SKIP LOCKED
|
||||
) AS c
|
||||
WHERE t.id = c.id
|
||||
RETURNING t.id, t.tenant_id, t.target_user_id, t.scene, t.title, t.content, t.push_attempts`,
|
||||
RETURNING t.id, t.tenant_id, t.target_user_id, t.scene, t.title, t.content, t.link_url, t.link_token, t.push_attempts`,
|
||||
pushStatusSending, pushStatusPending, s.cfg.DispatchBatch).
|
||||
Scan(&claimed).Error
|
||||
if err != nil {
|
||||
@@ -650,7 +656,7 @@ func (s *TrainingScheduler) dispatchTenant(ctx context.Context, tenantID uint64,
|
||||
case mapping[row.TargetUserID] == "":
|
||||
s.finishPush(ctx, row, pushStatusSkipped, nil, "缺少企微 userid 绑定")
|
||||
default:
|
||||
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, row.Content)
|
||||
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, wecomDispatchContent(row))
|
||||
if err == nil {
|
||||
s.finishPush(ctx, row, pushStatusSent, ptrTime(s.now()), "")
|
||||
continue
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
@@ -18,9 +19,9 @@ import (
|
||||
// fakeWecomBackend serves a fake sender plus a userid mapping to the
|
||||
// scheduler under test.
|
||||
type fakeWecomBackend struct {
|
||||
sender *fakePushSender
|
||||
sender *fakePushSender
|
||||
clientErr error
|
||||
mapping map[string]string
|
||||
mapping map[string]string
|
||||
lookupErr error
|
||||
}
|
||||
|
||||
@@ -40,15 +41,17 @@ func (f *fakeWecomBackend) TenantWecomUserIDs(context.Context, *gorm.DB, uint64,
|
||||
|
||||
// fakePushSender records SendMarkdown calls for dispatcher assertions.
|
||||
type fakePushSender struct {
|
||||
sent [][]string
|
||||
err error
|
||||
sent [][]string
|
||||
contents []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, _ string) error {
|
||||
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, content string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.sent = append(f.sent, userIDs)
|
||||
f.contents = append(f.contents, content)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -332,3 +335,54 @@ func TestRemindContent(t *testing.T) {
|
||||
require.Contains(t, maintain, "课程维护提醒")
|
||||
require.True(t, strings.Contains(maintain, "课件"), "maintain copy mentions materials")
|
||||
}
|
||||
|
||||
// [2026-11 需求] demand_collect 企微投递正文:行内带 link_url/link_token 时
|
||||
// 尾部拼「下载模板 + 查看详情」两行 markdown 链接;其他场景原样透传。
|
||||
func TestWecomDispatchContentDemandCollectFooter(t *testing.T) {
|
||||
token, err := utils.SignTrainingTemplateToken(&utils.TrainingTemplateTokenPayload{
|
||||
TenantID: 42, TemplateKey: types.TrainingTemplateDemandCollection,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("footer appended with download and details links", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneDemandCollect,
|
||||
Content: "请于 2027-01-31 前提报需求。", LinkURL: "https://aido.example.com", LinkToken: token}
|
||||
got := wecomDispatchContent(row)
|
||||
require.True(t, strings.HasPrefix(got, "请于 2027-01-31 前提报需求。"))
|
||||
require.Contains(t, got,
|
||||
"[下载教育训练需求表模板](https://aido.example.com"+utils.TrainingTemplateSignedFilePath+"?token="+token+")")
|
||||
require.Contains(t, got, "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
})
|
||||
|
||||
t.Run("missing token keeps details link only", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneDemandCollect,
|
||||
Content: "c", LinkURL: "https://aido.example.com"}
|
||||
got := wecomDispatchContent(row)
|
||||
require.NotContains(t, got, "signed-file")
|
||||
require.Contains(t, got, "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
})
|
||||
|
||||
t.Run("other scenes pass through untouched", func(t *testing.T) {
|
||||
row := &claimedNotification{Scene: types.SceneSessionNoticeStudent,
|
||||
Content: "markdown body", LinkURL: "https://aido.example.com", LinkToken: token}
|
||||
require.Equal(t, "markdown body", wecomDispatchContent(row))
|
||||
})
|
||||
|
||||
t.Run("dispatch end-to-end sends composed markdown", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-1", Scene: types.SceneDemandCollect, Content: "c",
|
||||
LinkURL: "https://aido.example.com", LinkToken: token, PushStatus: pushStatusSending}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID,
|
||||
[]*claimedNotification{{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1",
|
||||
Scene: types.SceneDemandCollect, Content: "c",
|
||||
LinkURL: "https://aido.example.com", LinkToken: token}})
|
||||
|
||||
require.Len(t, f.backend.sender.contents, 1)
|
||||
require.Contains(t, f.backend.sender.contents[0], "[查看更多详情>>](https://aido.example.com/platform/training/plan)")
|
||||
require.Contains(t, f.backend.sender.contents[0], "signed-file?token=")
|
||||
})
|
||||
}
|
||||
@@ -123,16 +123,84 @@ const (
|
||||
// demandTitleYearRe 标题行年份(如「2026 年 度 教 育 训 练 需 求 表」)。
|
||||
var demandTitleYearRe = regexp.MustCompile(`20\d{2}`)
|
||||
|
||||
// demandTemplateNoteText 说明列文案(2026-11 模板调整):备注右侧合并单元格,
|
||||
// 调研维度(战略/组织/员工三层)+ 各部门培训策划硬性要求。
|
||||
const demandTemplateNoteText = "注:调研维度:战略层(对齐高层对企业长期能力要求)、组织层(各部门业务迭代所需的协作与专业能力)、员工层(个人职业成长技能缺口)。\n" +
|
||||
"注:总务须策划全厂安全培训;\n" +
|
||||
" 品保须策划环境有害物质管理等培训;\n" +
|
||||
" 生产各工段须提供本工段相关的三级安全培训、技能培训等;\n" +
|
||||
"教育训练须涵盖技能、安全、质量、环境、环保、节能等方面。"
|
||||
|
||||
// normalizeDemandTemplateLayout 收集模板版式归一(纯 xlsx 操作,便于单测):
|
||||
// 旧口径文件(内置默认/租户自定义版,F2 为「培訓費用(RMB)」)删除费用列——
|
||||
// RemoveCol(F) 右侧各列整体左移一位(合并单元格/数据验证随列平移),归一为
|
||||
//
|
||||
// A编号 B部门 C课程名称 D适合人员 E地点 F内/外培训 G计划培训月份 H讲师 I备注;
|
||||
//
|
||||
// 新口径文件(F2 已是内/外培训)跳过。返回是否执行了删列。
|
||||
func normalizeDemandTemplateLayout(f *excelize.File, sheet string) bool {
|
||||
if val, _ := f.GetCellValue(sheet, "F2"); !strings.Contains(val, "費用") && !strings.Contains(val, "费用") {
|
||||
return false
|
||||
}
|
||||
_ = f.RemoveCol(sheet, "F")
|
||||
return true
|
||||
}
|
||||
|
||||
// writeDemandNoteColumn 收集模板说明列(纯 xlsx 操作,便于单测):定位表头行
|
||||
// 「备注」列(标准版式 I 列,非标准按表头扫描)右一列,写入调研维度/培训策划
|
||||
// 要求文案并合并至数据区末行(边框+自动换行+顶端对齐)。说明列已被占用或
|
||||
// 自定义模板已带「调研维度」文案时跳过,不覆盖租户内容。
|
||||
func writeDemandNoteColumn(f *excelize.File, sheet string) {
|
||||
noteCol := "J"
|
||||
if val, _ := f.GetCellValue(sheet, "I2"); !strings.Contains(val, "备注") && !strings.Contains(val, "備注") {
|
||||
// 非标准版式:按表头行扫描「备注」列,说明列取其右一列
|
||||
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"} {
|
||||
if val, _ := f.GetCellValue(sheet, col+"2"); strings.Contains(val, "备注") || strings.Contains(val, "備注") {
|
||||
idx, _ := excelize.ColumnNameToNumber(col)
|
||||
noteCol, _ = excelize.ColumnNumberToName(idx + 1)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for r := 1; r <= 3; r++ {
|
||||
val, _ := f.GetCellValue(sheet, noteCol+strconv.Itoa(r))
|
||||
if strings.Contains(val, "调研维度") || strings.TrimSpace(val) != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 合并至数据区末行(内置模板编号 1~12 + 带边框空行,数据区为 4~22 行;
|
||||
// 自定义模板版式差异时同样取 2~22 行为说明块,可预期、不随行数放大)。
|
||||
const noteLastRow = 22
|
||||
_ = f.SetCellValue(sheet, noteCol+"2", demandTemplateNoteText)
|
||||
_ = f.MergeCell(sheet, noteCol+"2", fmt.Sprintf("%s%d", noteCol, noteLastRow))
|
||||
styleID, err := f.NewStyle(&excelize.Style{
|
||||
Alignment: &excelize.Alignment{WrapText: true, Vertical: "top", Horizontal: "left"},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Style: 1, Color: "000000"},
|
||||
{Type: "right", Style: 1, Color: "000000"},
|
||||
{Type: "top", Style: 1, Color: "000000"},
|
||||
{Type: "bottom", Style: 1, Color: "000000"},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
_ = f.SetCellStyle(sheet, noteCol+"2", fmt.Sprintf("%s%d", noteCol, noteLastRow), styleID)
|
||||
}
|
||||
_ = f.SetColWidth(sheet, noteCol, noteCol, 45)
|
||||
}
|
||||
|
||||
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)动态注入:
|
||||
// - 版式归一(2026-11 调整):旧口径含「培训费用(RMB)」列的先删列(右侧列左移),
|
||||
// 归一为 A编号 B部门 C课程名称 D适合人员 E地点 F内/外培训 G计划培训月份
|
||||
// H讲师 I备注;备注(J)右侧写调研维度/培训策划说明列(writeDemandNoteColumn);
|
||||
// - 标题年份改为下一年度(收集模板面向下年度计划,如 2026 年下载即 2027);
|
||||
// - 「计划培训时间」(H 列)表头改为「计划培训月份」,下拉=1~12 月;
|
||||
// - 「计划培训时间」(G 列)表头改为「计划培训月份」,下拉=1~12 月;
|
||||
// - 「参加人员」(D 列)表头归一为「适合人员」(000154 新口径,兼容旧自定义模板);
|
||||
// - 「內/外培訓」(G 列)表头归一为「内/外培训」,下拉=内部/外部;
|
||||
// - 「內/外培訓」(F 列)表头归一为「内/外培训」,下拉=内部/外部;
|
||||
// - 「课程名称」(C 列)下拉按 B 列所选部门联动(OFFSET+MATCH 引用课程查找表,
|
||||
// 仅列该部门课程;非阻断式,也可直接填写新课程);
|
||||
// - 「适合人员」(D 列)「讲师」(I 列)按所选课程 VLOOKUP 自动带出(可改写,
|
||||
// 改后按填写值导入);I 列同时保留员工档案人员下拉;
|
||||
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(I 列)下拉=员工档案人员姓名
|
||||
// - 「适合人员」(D 列)「讲师」(H 列)按所选课程 VLOOKUP 自动带出(可改写,
|
||||
// 改后按填写值导入);H 列同时保留员工档案人员下拉;
|
||||
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(H 列)下拉=员工档案人员姓名
|
||||
// (联查 users 优先取 display_name 真实姓名,回退 username 工号;去重去空)。
|
||||
//
|
||||
// 取值写入同表隐藏辅助列(CA/CC + 课程查找表 CE~CH),以数据验证/公式呈现
|
||||
@@ -149,8 +217,13 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
sheet := sheets[0]
|
||||
|
||||
// 版式归一(2026-11 模板调整):旧口径含「培训费用(RMB)」列的文件先删列,
|
||||
// 之后所有列引用按新口径 A编号 B部门 C课程名称 D适合人员 E地点
|
||||
// F内/外培训 G计划培训月份 H讲师 I备注(备注右侧说明列见 writeDemandNoteColumn)。
|
||||
normalizeDemandTemplateLayout(f, sheet)
|
||||
|
||||
// 标题年份:面向下一年度收集(2026 年打开即 2027 年度教育训练需求表)。
|
||||
// 标题合并于 B1:J1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
|
||||
// 标题合并于 B1:I1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
|
||||
nextYear := time.Now().Year() + 1
|
||||
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"} {
|
||||
val, _ := f.GetCellValue(sheet, col+"1")
|
||||
@@ -161,18 +234,18 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训时间」表头改「计划培训月份」(H2 合并单元格左上角取值)。
|
||||
if val, _ := f.GetCellValue(sheet, "H2"); strings.Contains(val, "计划培训时间") {
|
||||
_ = f.SetCellValue(sheet, "H2", "计划培训月份")
|
||||
// 「计划培训时间」表头改「计划培训月份」(G2 合并单元格左上角取值)。
|
||||
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "计划培训时间") {
|
||||
_ = f.SetCellValue(sheet, "G2", "计划培训月份")
|
||||
}
|
||||
|
||||
// 表头归一(000154,兼容旧版自定义模板):「参加人员」D2 → 「适合人员」,
|
||||
// 「內/外培訓」G2 → 「内/外培训」(繁体转简体+新文案)。
|
||||
// 「內/外培訓」F2 → 「内/外培训」(繁体转简体+新文案)。
|
||||
if val, _ := f.GetCellValue(sheet, "D2"); strings.Contains(val, "参加人员") {
|
||||
_ = f.SetCellValue(sheet, "D2", "适合人员")
|
||||
}
|
||||
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
|
||||
_ = f.SetCellValue(sheet, "G2", "内/外培训")
|
||||
if val, _ := f.GetCellValue(sheet, "F2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
|
||||
_ = f.SetCellValue(sheet, "F2", "内/外培训")
|
||||
}
|
||||
|
||||
// 下拉取值:组织架构部门 + 课程管理课程 + 员工档案人员(去重、去空)
|
||||
@@ -237,10 +310,11 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
// (含历史版本注入的),避免叠加。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("D4:D%d", demandTargetRows+3))
|
||||
|
||||
// 「内/外培训」(G 列)先清既有验证再挂固定下拉,避免旧版模板叠加重复下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
// 「课程名称」(C 列)清既有验证(历史版本注入过扁平课程下拉),换部门联动下拉。
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("C4:C%d", demandTargetRows+3))
|
||||
// 清既有验证(兼容租户上传过带验证的自定义模板与历史注入):
|
||||
// C 课程名称 / F 内外培训 / G 计划培训月份 / H 讲师,再统一重挂,避免叠加重复下拉。
|
||||
for _, col := range []string{"C", "F", "G", "H"} {
|
||||
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s4:%s%d", col, col, demandTargetRows+3))
|
||||
}
|
||||
|
||||
// 写隐藏辅助列并以数据验证下拉挂到对应列。
|
||||
// 下拉为非阻断式(ShowErrorMessage=false,NewDataValidation 默认):单元格可
|
||||
@@ -271,11 +345,11 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
}
|
||||
applyList(demandOptColDept, "部门(组织架构)", deptNames, fmt.Sprintf("B4:B%d", demandTargetRows+3), "")
|
||||
applyList(demandOptColLect, "培训讲师(员工档案)", empNames,
|
||||
fmt.Sprintf("I4:I%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
fmt.Sprintf("H4:H%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
|
||||
|
||||
// 课程联动(000156):查找表写 CE~CH 隐藏列后——
|
||||
// C 列下拉 = OFFSET+MATCH 按 B 列所选部门联动该部门课程(同部门课程连续分组);
|
||||
// D 列 = VLOOKUP 带出课程「适合人员」,I 列 = 带出「讲师」;单元格可改写,
|
||||
// D 列 = VLOOKUP 带出课程「适合人员」,H 列 = 带出「讲师」;单元格可改写,
|
||||
// 改写后按填写值导入(导入解析取单元格显示值)。
|
||||
if n := len(courseRows); n > 0 {
|
||||
last := n + 1 // 查找表数据末行(表头占第 1 行)
|
||||
@@ -308,34 +382,37 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
|
||||
)
|
||||
dvCourse.SetInput("课程名称(按部门联动)", "先选部门,课程名称下拉即列出该部门课程;也可直接填写新课程")
|
||||
_ = f.AddDataValidation(sheet, dvCourse)
|
||||
// D/I 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
|
||||
// D/H 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
|
||||
for i := 0; i < demandTargetRows; i++ {
|
||||
r := i + 4
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("D%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,3,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("I%d", r),
|
||||
_ = f.SetCellFormula(sheet, fmt.Sprintf("H%d", r),
|
||||
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,4,0),""))`,
|
||||
r, r, demandLookupColName, demandLookupColLect, last))
|
||||
}
|
||||
}
|
||||
|
||||
// 「计划培训月份」(H 列)下拉=1~12(内联列表,非阻断式可自由填写)。
|
||||
// 「计划培训月份」(G 列)下拉=1~12(内联列表,非阻断式可自由填写)。
|
||||
dv := excelize.NewDataValidation(true)
|
||||
dv.SetSqref(fmt.Sprintf("H4:H%d", demandTargetRows+3))
|
||||
dv.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
dv.Type = "list"
|
||||
dv.Formula1 = `"1,2,3,4,5,6,7,8,9,10,11,12"`
|
||||
dv.SetInput("计划培训月份", "从下拉选择 1~12 月;导入后自动按「标题年份-月份」入库(如 2027-1)")
|
||||
_ = f.AddDataValidation(sheet, dv)
|
||||
|
||||
// 「内/外培训」(G 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
|
||||
// 「内/外培训」(F 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
|
||||
dvTrain := excelize.NewDataValidation(true)
|
||||
dvTrain.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
|
||||
dvTrain.SetSqref(fmt.Sprintf("F4:F%d", demandTargetRows+3))
|
||||
dvTrain.Type = "list"
|
||||
dvTrain.Formula1 = `"内部,外部"`
|
||||
dvTrain.SetInput("内/外培训", "从下拉选择内部或外部;留空视为未选择")
|
||||
_ = f.AddDataValidation(sheet, dvTrain)
|
||||
|
||||
// 备注(I)右侧说明列:调研维度 + 各部门培训策划要求(2026-11 模板调整)。
|
||||
writeDemandNoteColumn(f, sheet)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
if err != nil {
|
||||
return base
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/xuri/excelize/v2"
|
||||
|
||||
"academy/internal/assets/trainingtemplates"
|
||||
)
|
||||
|
||||
// 收集模板版式归一 + 说明列(2026-11 模板调整,normalizeDemandTemplateLayout /
|
||||
// writeDemandNoteColumn 的纯 xlsx 行为):旧口径文件删「培训费用」列后右侧
|
||||
// 整体左移,备注右侧写调研维度/培训策划说明列(合并至数据区末行)。
|
||||
func TestNormalizeDemandTemplateLayoutAndNoteColumn(t *testing.T) {
|
||||
data, err := trainingtemplates.Default("demand_collection")
|
||||
require.NoError(t, err)
|
||||
f, err := excelize.OpenReader(bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
defer f.Close()
|
||||
sheet := f.GetSheetList()[0]
|
||||
|
||||
// 旧口径:F2 = 培訓費用(RMB)
|
||||
v, _ := f.GetCellValue(sheet, "F2")
|
||||
require.Contains(t, v, "費用")
|
||||
|
||||
require.True(t, normalizeDemandTemplateLayout(f, sheet))
|
||||
// 删列后归一:F=内/外培训(繁简口径均可) G=计划培训时间(下载时再归一文案)
|
||||
// H=讲师 I=备注
|
||||
v, _ = f.GetCellValue(sheet, "F2")
|
||||
require.True(t, strings.Contains(v, "培训") || strings.Contains(v, "培訓"), "F2 应为内/外培训列,实际 %q", v)
|
||||
v, _ = f.GetCellValue(sheet, "G2")
|
||||
require.Contains(t, v, "计划培训时间")
|
||||
v, _ = f.GetCellValue(sheet, "H2")
|
||||
require.Contains(t, v, "讲师")
|
||||
v, _ = f.GetCellValue(sheet, "I2")
|
||||
require.Contains(t, v, "备注")
|
||||
// 已是新口径:F2 不再是费用列,不重复删列
|
||||
require.False(t, normalizeDemandTemplateLayout(f, sheet))
|
||||
|
||||
// 合并单元格/数据验证随删列平移:标题 B1:J1 → B1:I1,
|
||||
// 内置「内/外培训」下拉 G4:G503 → F4:F503(新口径的内/外培训列位)
|
||||
merges, err := f.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
titleMerged := false
|
||||
for _, m := range merges {
|
||||
if m.GetStartAxis() == sheet+"!B1" || m.GetStartAxis() == "B1" {
|
||||
titleMerged = true
|
||||
require.Equal(t, "I1", m.GetEndAxis())
|
||||
}
|
||||
}
|
||||
require.True(t, titleMerged)
|
||||
dvs, err := f.GetDataValidations(sheet)
|
||||
require.NoError(t, err)
|
||||
trainDv := false
|
||||
for _, dvObj := range dvs {
|
||||
if dvObj.Sqref == "F4:F503" {
|
||||
trainDv = true
|
||||
}
|
||||
}
|
||||
require.True(t, trainDv, "内置内外培训下拉应平移至 F4:F503")
|
||||
|
||||
writeDemandNoteColumn(f, sheet)
|
||||
|
||||
buf, err := f.WriteToBuffer()
|
||||
require.NoError(t, err)
|
||||
f2, err := excelize.OpenReader(bytes.NewReader(buf.Bytes()))
|
||||
require.NoError(t, err)
|
||||
defer f2.Close()
|
||||
|
||||
// 说明列:J2 写入调研维度/培训策划要求文案,合并至数据区末行(数据区 4~22 行)
|
||||
v, _ = f2.GetCellValue(sheet, "J2")
|
||||
require.Contains(t, v, "调研维度")
|
||||
require.Contains(t, v, "战略层")
|
||||
require.Contains(t, v, "总务须策划全厂安全培训")
|
||||
require.Contains(t, v, "教育训练须涵盖技能、安全、质量、环境、环保、节能等方面")
|
||||
noteMerges, err := f2.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
noteMerged := false
|
||||
for _, m := range noteMerges {
|
||||
if m.GetStartAxis() == sheet+"!J2" || m.GetStartAxis() == "J2" {
|
||||
noteMerged = true
|
||||
require.Equal(t, "J22", m.GetEndAxis())
|
||||
}
|
||||
}
|
||||
require.True(t, noteMerged)
|
||||
|
||||
// 重复写入跳过:说明列已占用,不覆盖(合并数保持不变)
|
||||
writeDemandNoteColumn(f2, sheet)
|
||||
merges2, err := f2.GetMergeCells(sheet)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, merges2, len(noteMerges))
|
||||
v, _ = f2.GetCellValue(sheet, "J2")
|
||||
require.Contains(t, v, "调研维度")
|
||||
}
|
||||
Reference in new issue
Block a user