feat: 接入商务用户资料和全局统计偏好

This commit is contained in:
Yvan
2026-11-03 17:44:25 +08:00
parent 89cc7761b5
commit ce4b54a2e2
39 changed files with 2562 additions and 17 deletions
+61
View File
@@ -0,0 +1,61 @@
package business
import (
"context"
"github.com/go-kratos/kratos/v3/errors"
"kra/internal/biz/system"
)
var (
ErrUnauthenticated = errors.Unauthorized("SW_UNAUTHENTICATED", "请先登录")
ErrPreferenceRequired = errors.BadRequest("SW_PREFERENCE_REQUIRED", "偏好参数不能为空")
ErrStorage = errors.InternalServer("SW_STORAGE_ERROR", "商务数据访问失败")
)
// UserPreference 使用新用户 ID,保留旧商务两个全局开关的含义。
type UserPreference struct {
IncludeSubPromote bool
IDCardDedup bool
}
type UserPreferenceRepo interface {
Find(context.Context, uint) (*UserPreference, error)
Save(context.Context, uint, UserPreference) error
}
type UserPreferenceUsecase struct{ repo UserPreferenceRepo }
func NewUserPreferenceUsecase(repo UserPreferenceRepo) *UserPreferenceUsecase {
return &UserPreferenceUsecase{repo: repo}
}
func (uc *UserPreferenceUsecase) Current(ctx context.Context) (*UserPreference, error) {
actor, ok := system.ActorFromContext(ctx)
if !ok || actor.UserID == 0 {
return nil, ErrUnauthenticated
}
return uc.ForUser(ctx, actor.UserID)
}
func (uc *UserPreferenceUsecase) ForUser(ctx context.Context, id uint) (*UserPreference, error) {
if id == 0 {
return nil, ErrUnauthenticated
}
pref, err := uc.repo.Find(ctx, id)
if err != nil {
return nil, err
}
if pref == nil {
return &UserPreference{IncludeSubPromote: true, IDCardDedup: true}, nil
}
return pref, nil
}
func (uc *UserPreferenceUsecase) UpdateCurrent(ctx context.Context, pref UserPreference) error {
actor, ok := system.ActorFromContext(ctx)
if !ok || actor.UserID == 0 {
return ErrUnauthenticated
}
return uc.repo.Save(ctx, actor.UserID, pref)
}
+43
View File
@@ -0,0 +1,43 @@
package business
import (
"context"
"kra/internal/biz/system"
"testing"
)
type preferenceRepoFake struct {
value *UserPreference
userID uint
calls int
}
func (r *preferenceRepoFake) Find(_ context.Context, id uint) (*UserPreference, error) {
r.calls++
r.userID = id
return r.value, nil
}
func (r *preferenceRepoFake) Save(_ context.Context, id uint, pref UserPreference) error {
r.calls++
r.userID, r.value = id, &pref
return nil
}
func TestPreferenceDefaultsAndCurrentIdentity(t *testing.T) {
r := &preferenceRepoFake{}
uc := NewUserPreferenceUsecase(r)
if _, err := uc.Current(context.Background()); err != ErrUnauthenticated || r.calls != 0 {
t.Fatalf("匿名请求访问了偏好: %v", err)
}
ctx := system.NewActorContext(context.Background(), system.Actor{UserID: 7})
pref, err := uc.Current(ctx)
if err != nil || !pref.IncludeSubPromote || !pref.IDCardDedup {
t.Fatalf("缺省开关应均为开启: %+v %v", pref, err)
}
if err = uc.UpdateCurrent(ctx, UserPreference{}); err != nil {
t.Fatal(err)
}
if r.userID != 7 || r.value.IncludeSubPromote || r.value.IDCardDedup {
t.Fatalf("未保存当前用户的关闭值: %+v", r)
}
}