Files
ai_academy/internal/application/repository/training.go
T
runny 0819f8c4d1 feat(training): 需求联动课程管理、适合人员多选、跨空间参与与计划讲师回写(000158-000161)
000158 需求单联动课程管理:
- tr_demands 新增 library_course_id:填报/导入按课程名称在课程管理精准匹配,
  命中自动关联,未命中自动新增待核验课程(000157 流转,发布前须签核完成);
  匹配/建档失败整批回滚并透出原因,不静默跳过
- 需求所属部门强制为填报人本人部门:新建按提报人档案落库(忽略请求值防绕过,
  无部门档案阻断),编辑保留原部门;批量导入按 Excel「部门」列做归属校验
- 编辑时课程名未变保留原课程关联,全量更新不误清

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

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

000161 计划讲师回写与发布校验:
- 月培训计划讲师计划侧可改,改动回写课程管理主数据并重置待核验(发布前须
  重新签核),同步补讲师 lecturer 角色绑定
- 发布必填校验:关联课程管理且已签核、参加人员;线下计划另需授课时间/地点/
  讲师(线上计划豁免);跨场次名单去重成员数校验
2026-11-24 10:03:58 +08:00

376 lines
16 KiB
Go

package repository
import (
"context"
"errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// trainingRepository 培训业务域数据访问。实现按域拆分在
// training.go / training_plan_course.go / training_exam_dash.go 三个文件。
// 所有查询都按 tenant_id 过滤,与框架租户隔离惯例保持一致。
type trainingRepository struct {
db *gorm.DB
}
// NewTrainingRepository constructs the production training repository.
func NewTrainingRepository(db *gorm.DB) interfaces.TrainingRepository {
return &trainingRepository{db: db}
}
// ---------------------------------------------------------------------------
// 组织联查(共享组织中心表;部门/名册管理已迁 orgcenter.go)
// ---------------------------------------------------------------------------
// GetMember fetches one member profile by ID.
func (r *trainingRepository) GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
First(&m).Error; err != nil {
return nil, err
}
return &m, nil
}
// GetMemberByUserID fetches one member profile by the platform user ID.
func (r *trainingRepository) GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
First(&m).Error; err != nil {
return nil, err
}
return &m, nil
}
// FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160):
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
// 同一组织的人员不因所在工作区不同而看不到企业培训。无档案返回 0,nil。
func (r *trainingRepository) FindArchiveTenantID(ctx context.Context, userID string) (uint64, error) {
var tenantIDs []uint64
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
Where("user_id = ? AND status = ?", userID, "active").
Order("created_at ASC").Limit(1).
Pluck("tenant_id", &tenantIDs).Error
if err != nil {
return 0, err
}
if len(tenantIDs) == 0 {
return 0, nil
}
return tenantIDs[0], nil
}
// ---------------------------------------------------------------------------
// 学习/积分/规则/通知
// ---------------------------------------------------------------------------
// UpsertLearningTask creates or refreshes an online learning task.
func (r *trainingRepository) UpsertLearningTask(ctx context.Context, task *types.TrainingLearningTask) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "course_id"}, {Name: "member_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"deadline": gorm.Expr("EXCLUDED.deadline"),
"remind_rule": gorm.Expr("EXCLUDED.remind_rule"),
"status": gorm.Expr("EXCLUDED.status"),
"completed_at": gorm.Expr("EXCLUDED.completed_at"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(task).Error
}
// ListLearningTasks returns the member's learning tasks with course names.
func (r *trainingRepository) ListLearningTasks(ctx context.Context, tenantID uint64, memberID string) ([]*types.TrainingLearningTask, error) {
var tasks []*types.TrainingLearningTask
err := r.db.WithContext(ctx).
Table("tr_learning_tasks t").
Select("t.*, COALESCE(c.name, '') AS course_name").
Joins("LEFT JOIN tr_courses c ON c.id = t.course_id AND c.tenant_id = t.tenant_id").
Where("t.tenant_id = ? AND t.member_id = ? AND t.deleted_at IS NULL", tenantID, memberID).
Order("t.deadline ASC NULLS LAST").
Scan(&tasks).Error
return tasks, err
}
// ListCourseLearningTasks returns all members' learning tasks of one course
// (管理端「学习考试」课程学习情况视图,附员工编号/岗位/部门名展示字段)。
func (r *trainingRepository) ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error) {
var tasks []*types.TrainingLearningTask
err := r.db.WithContext(ctx).
Table("tr_learning_tasks t").
Select(`t.*, COALESCE(c.name, '') AS course_name,
COALESCE(e.employee_no, '') AS employee_no, COALESCE(e.post, '') AS post,
COALESCE(dp.name, '') AS dept_name`).
Joins("LEFT JOIN tr_courses c ON c.id = t.course_id AND c.tenant_id = t.tenant_id").
Joins("LEFT JOIN org_employees e ON e.id = t.member_id AND e.tenant_id = t.tenant_id AND e.deleted_at IS NULL").
Joins("LEFT JOIN org_depts dp ON dp.id = e.dept_id AND dp.tenant_id = e.tenant_id AND dp.deleted_at IS NULL").
Where("t.tenant_id = ? AND t.course_id = ? AND t.deleted_at IS NULL", tenantID, courseID).
Order("t.status ASC, t.deadline ASC NULLS LAST").
Scan(&tasks).Error
return tasks, err
}
// LecturerMonthStats aggregates per-lecturer session counts of a month.
func (r *trainingRepository) LecturerMonthStats(ctx context.Context, tenantID uint64, year, month int) ([]*types.TrainingLecturerMonthStat, error) {
var rows []*types.TrainingLecturerMonthStat
err := r.db.WithContext(ctx).
Table("tr_course_sessions s").
Select(`s.lecturer_id,
COUNT(*) AS sessions_total,
COUNT(*) FILTER (WHERE s.status = 'finished') AS sessions_finished`).
Where("s.tenant_id = ? AND s.year = ? AND s.month = ? AND s.lecturer_id <> '' AND s.deleted_at IS NULL",
tenantID, year, month).
Group("s.lecturer_id").
Scan(&rows).Error
return rows, err
}
// UpsertLecturerScore stores one lecturer monthly score row.
func (r *trainingRepository) UpsertLecturerScore(ctx context.Context, score *types.TrainingLecturerScore) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "lecturer_id"}, {Name: "year"}, {Name: "month"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"on_time_score": gorm.Expr("EXCLUDED.on_time_score"),
"rating_score": gorm.Expr("EXCLUDED.rating_score"),
"qa_score": gorm.Expr("EXCLUDED.qa_score"),
"total": gorm.Expr("EXCLUDED.total"),
"rank_no": gorm.Expr("EXCLUDED.rank_no"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(score).Error
}
// UpsertLearningProgress stores the playback position of one material.
func (r *trainingRepository) UpsertLearningProgress(ctx context.Context, progress *types.TrainingLearningProgress) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "task_id"}, {Name: "material_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"position_sec": gorm.Expr("EXCLUDED.position_sec"),
"percent": gorm.Expr("EXCLUDED.percent"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(progress).Error
}
// ListProgressByCourse returns one member's per-material progress within a
// course (详情页续播/进度条回读)。
func (r *trainingRepository) ListProgressByCourse(ctx context.Context, tenantID uint64, memberID, courseID string) ([]*types.TrainingLearningProgress, error) {
var rows []*types.TrainingLearningProgress
err := r.db.WithContext(ctx).
Table("tr_learning_progress p").
Select("p.material_id, p.position_sec, p.percent").
Joins("JOIN tr_learning_tasks t ON t.id = p.task_id AND t.tenant_id = p.tenant_id").
Where("p.tenant_id = ? AND t.member_id = ? AND t.course_id = ?", tenantID, memberID, courseID).
Scan(&rows).Error
return rows, err
}
// AddPointRecord appends one point record (unique key dedups repeats).
func (r *trainingRepository) AddPointRecord(ctx context.Context, record *types.TrainingPointRecord) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(record).Error
}
// SumPointsByMember returns the member's total points.
func (r *trainingRepository) SumPointsByMember(ctx context.Context, tenantID uint64, memberID string) (int, error) {
var total int64
err := r.db.WithContext(ctx).Model(&types.TrainingPointRecord{}).
Where("tenant_id = ? AND member_id = ?", tenantID, memberID).
Select("COALESCE(SUM(points), 0)").Scan(&total).Error
return int(total), err
}
// SumPoints returns the tenant's total granted points.
func (r *trainingRepository) SumPoints(ctx context.Context, tenantID uint64) (int, error) {
var total int64
err := r.db.WithContext(ctx).Model(&types.TrainingPointRecord{}).
Where("tenant_id = ?", tenantID).
Select("COALESCE(SUM(points), 0)").Scan(&total).Error
return int(total), err
}
// GetRuleConfig returns one rule config by key.
func (r *trainingRepository) GetRuleConfig(ctx context.Context, tenantID uint64, key string) (*types.TrainingRuleConfig, error) {
var cfg types.TrainingRuleConfig
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND rule_key = ?", tenantID, key).
First(&cfg).Error; err != nil {
return nil, err
}
return &cfg, nil
}
// UpsertRuleConfig creates or updates one rule config.
func (r *trainingRepository) UpsertRuleConfig(ctx context.Context, cfg *types.TrainingRuleConfig) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "rule_key"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"rule_value": gorm.Expr("EXCLUDED.rule_value"),
"updated_by": gorm.Expr("EXCLUDED.updated_by"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(cfg).Error
}
// ListRuleConfigs returns all rule configs of the tenant.
func (r *trainingRepository) ListRuleConfigs(ctx context.Context, tenantID uint64) ([]*types.TrainingRuleConfig, error) {
var cfgs []*types.TrainingRuleConfig
err := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
Order("rule_key ASC").
Find(&cfgs).Error
return cfgs, err
}
// GetTrainingTemplate returns one custom uploaded template by key (not found → nil, nil).
func (r *trainingRepository) GetTrainingTemplate(ctx context.Context, tenantID uint64, key string) (*types.TrainingTemplate, error) {
var tpl types.TrainingTemplate
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND template_key = ?", tenantID, key).
First(&tpl).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &tpl, nil
}
// UpsertTrainingTemplate creates or replaces the custom template of a key.
// tr_templates 是部分唯一索引(WHERE deleted_at IS NULL),冲突目标需带同一谓词。
func (r *trainingRepository) UpsertTrainingTemplate(ctx context.Context, tpl *types.TrainingTemplate) error {
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "template_key"}},
TargetWhere: clause.Where{Exprs: []clause.Expression{
gorm.Expr("deleted_at IS NULL"),
}},
DoUpdates: clause.Assignments(map[string]interface{}{
"file_name": gorm.Expr("EXCLUDED.file_name"),
"file_size": gorm.Expr("EXCLUDED.file_size"),
"file_content": gorm.Expr("EXCLUDED.file_content"),
"updated_by": gorm.Expr("EXCLUDED.updated_by"),
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
}),
}).
Create(tpl).Error
}
// DeleteTrainingTemplate removes the custom template (download falls back to bundled default).
func (r *trainingRepository) DeleteTrainingTemplate(ctx context.Context, tenantID uint64, key string) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND template_key = ?", tenantID, key).
Delete(&types.TrainingTemplate{}).Error
}
// CreateNotification appends one notification row.
func (r *trainingRepository) CreateNotification(ctx context.Context, n *types.TrainingNotification) error {
return r.db.WithContext(ctx).Create(n).Error
}
// ListNotifications returns the target user's notifications, newest first.
func (r *trainingRepository) ListNotifications(ctx context.Context, tenantID uint64, targetUserID string, unreadOnly bool, limit int) ([]*types.TrainingNotification, error) {
if limit <= 0 || limit > 100 {
limit = 50
}
tx := r.db.WithContext(ctx).
Where("tenant_id = ? AND target_user_id = ?", tenantID, targetUserID)
if unreadOnly {
tx = tx.Where("read_at IS NULL")
}
var items []*types.TrainingNotification
err := tx.Order("sent_at DESC").Limit(limit).Find(&items).Error
return items, err
}
// MarkNotificationsRead marks all unread rows of the user as read.
func (r *trainingRepository) MarkNotificationsRead(ctx context.Context, tenantID uint64, targetUserID string) error {
return r.db.WithContext(ctx).Model(&types.TrainingNotification{}).
Where("tenant_id = ? AND target_user_id = ? AND read_at IS NULL", tenantID, targetUserID).
Update("read_at", gorm.Expr("CURRENT_TIMESTAMP")).Error
}
// CreateNotifications 批量追加通知行(开课通知/月度讲师提醒入队)。
// ON CONFLICT DO NOTHING:唯一索引 (tenant_id, target_user_id, scene, ref_id) 兜底并发幂等。
func (r *trainingRepository) CreateNotifications(ctx context.Context, rows []*types.TrainingNotification) error {
if len(rows) == 0 {
return nil
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(&rows).Error
}
// ListNotificationsByRef 返回某引用对象(场次 ID / 月份周次键)下已存在的通知行,
// 供写入方做幂等预检(已存在 target+scene 组合不再重发)。
func (r *trainingRepository) ListNotificationsByRef(ctx context.Context, tenantID uint64, refType, refID string) ([]*types.TrainingNotification, error) {
var items []*types.TrainingNotification
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND ref_type = ? AND ref_id = ? AND deleted_at IS NULL", tenantID, refType, refID).
Find(&items).Error
return items, err
}
// ListPushLogs 管理端逐人推送明细(推送管理台"推送记录"):按场景集合可选过滤,
// 时间倒序;push_status 空 = 仅站内不入企微外箱。
func (r *trainingRepository) ListPushLogs(ctx context.Context, tenantID uint64, scenes []string, refType string, limit int) ([]*types.TrainingNotification, error) {
if limit <= 0 || limit > 500 {
limit = 200
}
tx := r.db.WithContext(ctx).Model(&types.TrainingNotification{}).
Where("tenant_id = ? AND deleted_at IS NULL", tenantID)
if len(scenes) > 0 {
tx = tx.Where("scene IN ?", scenes)
}
if refType != "" {
tx = tx.Where("ref_type = ?", refType)
}
var items []*types.TrainingNotification
err := tx.Order("created_at DESC, id DESC").Limit(limit).Find(&items).Error
return items, err
}
// ListMonthActiveSessions 返回某年月仍活跃(未取消、未删除)的场次集合,
// 供"周一讲师未完成汇总提醒"扫描讲师名下未结束场次。
func (r *trainingRepository) ListMonthActiveSessions(ctx context.Context, tenantID uint64, year, month int) ([]*types.TrainingCourseSession, error) {
var items []*types.TrainingCourseSession
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND year = ? AND month = ? AND status IN ? AND deleted_at IS NULL",
tenantID, year, month,
[]string{types.TrainingSessionScheduled, types.TrainingSessionOngoing}).
Find(&items).Error
return items, err
}
// ListMembersByUserIDs 按平台用户 ID 集合取员工档案(联 users 取展示姓名),
// 供推送记录把 target_user_id 映射为人名/工号。
func (r *trainingRepository) ListMembersByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingMember, error) {
if len(userIDs) == 0 {
return []*types.TrainingMember{}, nil
}
var members []*types.TrainingMember
err := r.db.WithContext(ctx).
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
Select("org_employees.*, COALESCE(u.display_name, u.username) AS user_name").
Where("org_employees.tenant_id = ? AND org_employees.user_id IN ? AND org_employees.deleted_at IS NULL",
tenantID, userIDs).
Find(&members).Error
return members, err
}