85 lines
2.4 KiB
Go
85 lines
2.4 KiB
Go
package business
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/go-kratos/kratos/v3/errors"
|
|
"kra/internal/biz/system"
|
|
)
|
|
|
|
var (
|
|
ErrOtherSettingsScope = errors.Forbidden("SW_OTHER_SETTINGS_SCOPE", "仅超级管理员可以查看和修改其他设置")
|
|
ErrOtherSettingsInput = errors.BadRequest("SW_OTHER_SETTINGS_INPUT", "达标金额须为不小于0的整数,判定窗口须为不小于1的整数,且不能超过安全整数范围")
|
|
ErrOtherSettingsStored = errors.BadRequest("SW_OTHER_SETTINGS_STORED", "已保存的设置格式不正确,请恢复默认后重新保存")
|
|
)
|
|
|
|
const MaxSettingsInteger int64 = 9007199254740991
|
|
|
|
type OtherSettings struct {
|
|
Amount, Days int64
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
func DefaultOtherSettings() OtherSettings { return OtherSettings{Amount: 3000, Days: 30} }
|
|
|
|
func ValidateOtherSettings(value OtherSettings) error {
|
|
if value.Amount < 0 || value.Amount > MaxSettingsInteger || value.Days < 1 || value.Days > MaxSettingsInteger {
|
|
return ErrOtherSettingsInput
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type OtherSettingsRepo interface {
|
|
Find(context.Context) (*OtherSettings, error)
|
|
Save(context.Context, OtherSettings) (*OtherSettings, error)
|
|
}
|
|
|
|
type OtherSettingsUsecase struct {
|
|
repo OtherSettingsRepo
|
|
effectiveness *EffectivenessUsecase
|
|
}
|
|
|
|
func NewOtherSettingsUsecase(repo OtherSettingsRepo, effectiveness *EffectivenessUsecase) *OtherSettingsUsecase {
|
|
return &OtherSettingsUsecase{repo: repo, effectiveness: effectiveness}
|
|
}
|
|
|
|
func requireSettingsAdmin(ctx context.Context) error {
|
|
actor, ok := system.ActorFromContext(ctx)
|
|
if !ok || actor.UserID == 0 {
|
|
return ErrUnauthenticated
|
|
}
|
|
if actor.AuthorityID != system.SuperAdminAuthorityID {
|
|
return ErrOtherSettingsScope
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (uc *OtherSettingsUsecase) Get(ctx context.Context) (*OtherSettings, error) {
|
|
if err := requireSettingsAdmin(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
value, err := uc.repo.Find(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if value == nil {
|
|
defaults := DefaultOtherSettings()
|
|
return &defaults, nil
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
func (uc *OtherSettingsUsecase) Save(ctx context.Context, value OtherSettings) (*OtherSettings, error) {
|
|
if err := requireSettingsAdmin(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := ValidateOtherSettings(value); err != nil {
|
|
return nil, err
|
|
}
|
|
if uc.effectiveness != nil {
|
|
return uc.effectiveness.Reconfigure(ctx, value)
|
|
}
|
|
return uc.repo.Save(ctx, value)
|
|
}
|