Files
ai_academy/internal/application/repository/training.go
T
runny f43fbef5db
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
feat(企微签到):逻辑:员工使用企微扫码后直接跳出签到页面,在签到页面对该课程进行点击签到!
规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码);
补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
2026-11-25 11:02:48 +08:00

387 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
}
// GetMemberByWecomUserid 企微免登反查(2026-11 扫码签到):按绑定定位培训档案。
func (r *trainingRepository) GetMemberByWecomUserid(ctx context.Context, tenantID uint64, wecomUserid string) (*types.TrainingMember, error) {
var m types.TrainingMember
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND wecom_userid = ?", tenantID, wecomUserid).
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
}