63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
package business
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
"kra/internal/biz/business"
|
|
)
|
|
|
|
// Provider 复用 Data 持有的连接,不在仓储中创建数据库客户端。
|
|
type Provider interface{ DB() *gorm.DB }
|
|
|
|
type preferencePO struct {
|
|
UserID uint `gorm:"primaryKey;autoIncrement:false"`
|
|
IncludeSubPromote *int
|
|
IDCardDedup *int `gorm:"column:idcard_dedup"`
|
|
UpdateTime time.Time
|
|
}
|
|
|
|
func (preferencePO) TableName() string { return "sys_user_preference" }
|
|
|
|
type userPreferenceRepo struct{ data Provider }
|
|
|
|
func NewUserPreferenceRepo(data Provider) business.UserPreferenceRepo {
|
|
return &userPreferenceRepo{data: data}
|
|
}
|
|
|
|
func (r *userPreferenceRepo) Find(ctx context.Context, id uint) (*business.UserPreference, error) {
|
|
var po preferencePO
|
|
err := r.data.DB().WithContext(ctx).First(&po, "user_id = ?", id).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, business.ErrStorage
|
|
}
|
|
return &business.UserPreference{
|
|
IncludeSubPromote: po.IncludeSubPromote == nil || *po.IncludeSubPromote != 0,
|
|
IDCardDedup: po.IDCardDedup == nil || *po.IDCardDedup != 0,
|
|
}, nil
|
|
}
|
|
|
|
func (r *userPreferenceRepo) Save(ctx context.Context, id uint, pref business.UserPreference) error {
|
|
include, dedup := 0, 0
|
|
if pref.IncludeSubPromote {
|
|
include = 1
|
|
}
|
|
if pref.IDCardDedup {
|
|
dedup = 1
|
|
}
|
|
po := preferencePO{UserID: id, IncludeSubPromote: &include, IDCardDedup: &dedup, UpdateTime: time.Now()}
|
|
if err := r.data.DB().WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "user_id"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"include_sub_promote", "idcard_dedup", "update_time"}),
|
|
}).Create(&po).Error; err != nil {
|
|
return business.ErrStorage
|
|
}
|
|
return nil
|
|
}
|