You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.7 KiB
Go

package model
import (
"context"
"git.noahlan.cn/northlan/ntools-go/gorm-zero/gormx"
"git.noahlan.cn/northlan/ntools-go/uuid"
"github.com/jinzhu/now"
"github.com/pkg/errors"
"gorm.io/gorm"
"live-service/common/nerr"
"live-service/common/timex"
"time"
)
var _ UserEliteModel = (*customUserEliteModel)(nil)
type (
// UserEliteModel is an interface to be customized, add more methods here,
// and implement the added methods in customUserEliteModel.
UserEliteModel interface {
userEliteModel
// FindByUserId 查找用户所有列表
FindByUserId(ctx context.Context, tx *gorm.DB, userId int64) ([]UserElite, error)
// Addon 添加新的或延长时间
Addon(ctx context.Context, tx *gorm.DB, userId, eliteId int64, duration time.Duration, forever bool) error
}
customUserEliteModel struct {
*defaultUserEliteModel
}
)
// NewUserEliteModel returns a model for the database table.
func NewUserEliteModel(conn *gorm.DB) UserEliteModel {
return &customUserEliteModel{
defaultUserEliteModel: newUserEliteModel(conn),
}
}
func (m *customUserEliteModel) FindByUserId(ctx context.Context, tx *gorm.DB, userId int64) ([]UserElite, error) {
var resp []UserElite
err := gormx.WithTx(ctx, m.DB, tx).Table(m.table).
Where("user_id = ?", userId).Find(&resp).Error
err = gormx.WrapSelectErr(err)
if err != nil {
return nil, err
}
return resp, nil
}
func (m *customUserEliteModel) Addon(ctx context.Context, tx *gorm.DB, userId, eliteId int64, duration time.Duration, forever bool) error {
return m.TransactCtx(ctx, tx, func(tx *gorm.DB) error {
userElite, err := m.FindOneByUserIdEliteId(ctx, tx, userId, eliteId)
if err != nil {
if !errors.Is(err, gormx.ErrNotFound) {
return nerr.NewWithCode(nerr.DBError)
}
}
today := now.BeginningOfDay()
if userElite == nil {
err = m.Insert(ctx, tx, &UserElite{
Id: uuid.NextId(),
UserId: userId,
EliteId: eliteId,
Forever: BitBool(forever),
StartTime: today,
EndTime: today.Add(duration),
})
if err != nil {
return nerr.NewWithCode(nerr.DBError)
}
} else {
// update
if !timex.DayExpire(today, userElite.EndTime, bool(userElite.Forever)) {
// 未过期,endTime直接添加1day
userElite.EndTime = userElite.EndTime.Add(duration)
err = m.Update(ctx, tx, userElite)
if err != nil {
return nerr.NewWithCode(nerr.DBError)
}
} else {
// 过期,更新日期
err = m.Update(ctx, tx, &UserElite{
Id: userElite.Id,
UserId: userId,
EliteId: eliteId,
Forever: BitBool(forever),
StartTime: today,
EndTime: today.Add(duration),
})
if err != nil {
return nerr.NewWithCode(nerr.DBError)
}
}
}
return nil
})
}