feat(user-preferences): implement user preferences management with backend support

Added functionality for managing user preferences, including the ability to update preferences via a new API endpoint. The preferences are now stored server-side, allowing for synchronization across devices. Updated relevant components to handle user preferences, including the UserMenu and settings views. Enhanced internationalization support for error messages related to preference updates.
This commit is contained in:
wizardchen
2026-05-18 11:21:55 +08:00
committed by lyingbug
parent 3226cb97ff
commit 68ac7fb973
20 changed files with 301 additions and 24 deletions
+31
View File
@@ -494,6 +494,37 @@ func (s *userService) UpdateUser(ctx context.Context, user *types.User) error {
return s.userRepo.UpdateUser(ctx, user)
}
// UpdateUserPreferences applies a partial update over the user's
// preferences blob. PATCH semantics: only keys present in `patch`
// (non-nil pointer fields) replace the existing value; everything else
// is preserved. This lets the front-end PUT only the toggle that
// changed without having to read-modify-write the whole struct, and
// also makes the endpoint forward-compatible — older clients that
// don't know about newer keys won't accidentally erase them.
func (s *userService) UpdateUserPreferences(
ctx context.Context,
userID string,
patch types.UserPreferences,
) (types.UserPreferences, error) {
user, err := s.userRepo.GetUserByID(ctx, userID)
if err != nil {
return types.UserPreferences{}, err
}
merged := user.Preferences
if patch.EnableMemory != nil {
v := *patch.EnableMemory
merged.EnableMemory = &v
}
user.Preferences = merged
user.UpdatedAt = time.Now()
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
return types.UserPreferences{}, err
}
return merged, nil
}
// DeleteUser deletes a user
func (s *userService) DeleteUser(ctx context.Context, id string) error {
return s.userRepo.DeleteUser(ctx, id)
+55
View File
@@ -490,6 +490,61 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
})
}
// updateMyPreferencesRequest is the body for PUT /auth/me/preferences.
// Fields are pointers so the handler can distinguish "key not present"
// (preserve existing value) from "explicit false". See
// types.UserPreferences for the persistence-layer counterpart.
type updateMyPreferencesRequest struct {
EnableMemory *bool `json:"enable_memory"`
}
// UpdateMyPreferences godoc
// @Summary 更新当前用户的个性化设置
// @Description 按 PATCH 语义合并用户偏好(仅覆盖请求体里出现的字段,其余字段保持不变),
// @Description 数据存放在 users.preferences (JSON),跨设备/浏览器自动同步。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body updateMyPreferencesRequest true "Preferences patch"
// @Success 200 {object} map[string]interface{} "更新后的偏好"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 401 {object} errors.AppError "未授权"
// @Security Bearer
// @Router /auth/me/preferences [put]
func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {
ctx := c.Request.Context()
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
c.Error(appErr)
return
}
var req updateMyPreferencesRequest
if err := c.ShouldBindJSON(&req); err != nil {
appErr := errors.NewValidationError("Invalid preferences request").WithDetails(err.Error())
c.Error(appErr)
return
}
patch := types.UserPreferences{
EnableMemory: req.EnableMemory,
}
prefs, err := h.userService.UpdateUserPreferences(ctx, user.ID, patch)
if err != nil {
logger.Errorf(ctx, "Failed to update preferences for user %s: %v", user.Email, err)
appErr := errors.NewBadRequestError("Failed to update preferences").WithDetails(err.Error())
c.Error(appErr)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": prefs,
})
}
// ChangePassword godoc
// @Summary 修改密码
// @Description 修改当前用户的登录密码
+1
View File
@@ -654,6 +654,7 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.GET("/auth/validate", handler.ValidateToken)
r.POST("/auth/logout", handler.Logout)
r.GET("/auth/me", handler.GetCurrentUser)
r.PUT("/auth/me/preferences", handler.UpdateMyPreferences)
r.POST("/auth/change-password", handler.ChangePassword)
}
+4
View File
@@ -65,6 +65,10 @@ type UserService interface {
GetCurrentUser(ctx context.Context) (*types.User, error)
// SearchUsers searches users by username or email
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
// UpdateUserPreferences partially updates the calling user's
// preferences blob (PATCH semantics: only keys present in `patch`
// overwrite existing values). Returns the updated, persisted prefs.
UpdateUserPreferences(ctx context.Context, userID string, patch types.UserPreferences) (types.UserPreferences, error)
}
// UserRepository defines the user repository interface
+67 -9
View File
@@ -1,11 +1,63 @@
package types
import (
"database/sql/driver"
"encoding/json"
"errors"
"time"
"gorm.io/gorm"
)
// UserPreferences holds per-user UI/feature preferences persisted server-side
// so they sync across devices/browsers. Fields are pointers so we can
// distinguish "client didn't send this key" (leave existing value alone)
// from "client explicitly set false" — the partial-update merge in
// UpdateUserPreferences relies on this.
//
// Adding a new preference key:
// 1. Add a *T field below + JSON tag (snake_case, must match the front-end key).
// 2. Extend the merge logic in service.UserService.UpdateUserPreferences.
// 3. Surface the new knob in the frontend settings store.
// No DB DDL is required — preferences is a single jsonb column.
type UserPreferences struct {
// EnableMemory mirrors the "开启记忆功能" switch in General Settings.
// nil = preference never set (treat as feature default = false)
// *false / *true = user explicitly set the toggle.
EnableMemory *bool `json:"enable_memory,omitempty"`
}
// Value implements driver.Valuer so GORM persists UserPreferences as
// JSON text (Postgres jsonb column / SQLite TEXT). Empty struct serialises
// to "{}", matching the NOT NULL DEFAULT '{}' column constraint.
func (p UserPreferences) Value() (driver.Value, error) {
return json.Marshal(p)
}
// Scan implements sql.Scanner so GORM can hydrate UserPreferences back
// from the underlying column. Accept []byte (Postgres jsonb / SQLite blob)
// and string (some drivers hand TEXT as string) for portability.
func (p *UserPreferences) Scan(value interface{}) error {
if value == nil {
*p = UserPreferences{}
return nil
}
var data []byte
switch v := value.(type) {
case []byte:
data = v
case string:
data = []byte(v)
default:
return errors.New("UserPreferences.Scan: unsupported type")
}
if len(data) == 0 {
*p = UserPreferences{}
return nil
}
return json.Unmarshal(data, p)
}
// User represents a user in the system
type User struct {
// Unique identifier of the user
@@ -24,6 +76,10 @@ type User struct {
IsActive bool `json:"is_active" gorm:"default:true"`
// Whether the user can access all tenants (cross-tenant access)
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
// Per-user UI/feature preferences (memory toggle, future knobs).
// Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
// driver.Valuer / sql.Scanner methods on UserPreferences.
Preferences UserPreferences `json:"preferences" gorm:"type:jsonb;not null;default:'{}'"`
// Creation time of the user
CreatedAt time.Time `json:"created_at"`
// Last updated time of the user
@@ -140,15 +196,16 @@ type RegisterResponse struct {
// UserInfo represents user information for API responses
type UserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CanAccessAllTenants bool `json:"can_access_all_tenants"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CanAccessAllTenants bool `json:"can_access_all_tenants"`
Preferences UserPreferences `json:"preferences"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ToUserInfo converts User to UserInfo (without sensitive data)
@@ -161,6 +218,7 @@ func (u *User) ToUserInfo() *UserInfo {
TenantID: u.TenantID,
IsActive: u.IsActive,
CanAccessAllTenants: u.CanAccessAllTenants,
Preferences: u.Preferences,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
}