Merge PR #122: feat: 用户自定义属性系统 + Wechat 字段迁移
This commit is contained in:
@@ -246,7 +246,7 @@ func (h *UsageHandler) SearchUsers(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Limit to 30 results
|
||||
users, _, err := h.adminService.ListUsers(c.Request.Context(), 1, 30, "", "", keyword)
|
||||
users, _, err := h.adminService.ListUsers(c.Request.Context(), 1, 30, service.UserListFilters{Search: keyword})
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
|
||||
342
backend/internal/handler/admin/user_attribute_handler.go
Normal file
342
backend/internal/handler/admin/user_attribute_handler.go
Normal file
@@ -0,0 +1,342 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UserAttributeHandler handles user attribute management
|
||||
type UserAttributeHandler struct {
|
||||
attrService *service.UserAttributeService
|
||||
}
|
||||
|
||||
// NewUserAttributeHandler creates a new handler
|
||||
func NewUserAttributeHandler(attrService *service.UserAttributeService) *UserAttributeHandler {
|
||||
return &UserAttributeHandler{attrService: attrService}
|
||||
}
|
||||
|
||||
// --- Request/Response DTOs ---
|
||||
|
||||
// CreateAttributeDefinitionRequest represents create attribute definition request
|
||||
type CreateAttributeDefinitionRequest struct {
|
||||
Key string `json:"key" binding:"required,min=1,max=100"`
|
||||
Name string `json:"name" binding:"required,min=1,max=255"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type" binding:"required"`
|
||||
Options []service.UserAttributeOption `json:"options"`
|
||||
Required bool `json:"required"`
|
||||
Validation service.UserAttributeValidation `json:"validation"`
|
||||
Placeholder string `json:"placeholder"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// UpdateAttributeDefinitionRequest represents update attribute definition request
|
||||
type UpdateAttributeDefinitionRequest struct {
|
||||
Name *string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
Type *string `json:"type"`
|
||||
Options *[]service.UserAttributeOption `json:"options"`
|
||||
Required *bool `json:"required"`
|
||||
Validation *service.UserAttributeValidation `json:"validation"`
|
||||
Placeholder *string `json:"placeholder"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// ReorderRequest represents reorder attribute definitions request
|
||||
type ReorderRequest struct {
|
||||
IDs []int64 `json:"ids" binding:"required"`
|
||||
}
|
||||
|
||||
// UpdateUserAttributesRequest represents update user attributes request
|
||||
type UpdateUserAttributesRequest struct {
|
||||
Values map[int64]string `json:"values" binding:"required"`
|
||||
}
|
||||
|
||||
// BatchGetUserAttributesRequest represents batch get user attributes request
|
||||
type BatchGetUserAttributesRequest struct {
|
||||
UserIDs []int64 `json:"user_ids" binding:"required"`
|
||||
}
|
||||
|
||||
// BatchUserAttributesResponse represents batch user attributes response
|
||||
type BatchUserAttributesResponse struct {
|
||||
// Map of userID -> map of attributeID -> value
|
||||
Attributes map[int64]map[int64]string `json:"attributes"`
|
||||
}
|
||||
|
||||
// AttributeDefinitionResponse represents attribute definition response
|
||||
type AttributeDefinitionResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Options []service.UserAttributeOption `json:"options"`
|
||||
Required bool `json:"required"`
|
||||
Validation service.UserAttributeValidation `json:"validation"`
|
||||
Placeholder string `json:"placeholder"`
|
||||
DisplayOrder int `json:"display_order"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AttributeValueResponse represents attribute value response
|
||||
type AttributeValueResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
AttributeID int64 `json:"attribute_id"`
|
||||
Value string `json:"value"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
func defToResponse(def *service.UserAttributeDefinition) *AttributeDefinitionResponse {
|
||||
return &AttributeDefinitionResponse{
|
||||
ID: def.ID,
|
||||
Key: def.Key,
|
||||
Name: def.Name,
|
||||
Description: def.Description,
|
||||
Type: string(def.Type),
|
||||
Options: def.Options,
|
||||
Required: def.Required,
|
||||
Validation: def.Validation,
|
||||
Placeholder: def.Placeholder,
|
||||
DisplayOrder: def.DisplayOrder,
|
||||
Enabled: def.Enabled,
|
||||
CreatedAt: def.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
UpdatedAt: def.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
}
|
||||
|
||||
func valueToResponse(val *service.UserAttributeValue) *AttributeValueResponse {
|
||||
return &AttributeValueResponse{
|
||||
ID: val.ID,
|
||||
UserID: val.UserID,
|
||||
AttributeID: val.AttributeID,
|
||||
Value: val.Value,
|
||||
CreatedAt: val.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
UpdatedAt: val.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
}
|
||||
|
||||
// --- Handlers ---
|
||||
|
||||
// ListDefinitions lists all attribute definitions
|
||||
// GET /admin/user-attributes
|
||||
func (h *UserAttributeHandler) ListDefinitions(c *gin.Context) {
|
||||
enabledOnly := c.Query("enabled") == "true"
|
||||
|
||||
defs, err := h.attrService.ListDefinitions(c.Request.Context(), enabledOnly)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]*AttributeDefinitionResponse, 0, len(defs))
|
||||
for i := range defs {
|
||||
out = append(out, defToResponse(&defs[i]))
|
||||
}
|
||||
|
||||
response.Success(c, out)
|
||||
}
|
||||
|
||||
// CreateDefinition creates a new attribute definition
|
||||
// POST /admin/user-attributes
|
||||
func (h *UserAttributeHandler) CreateDefinition(c *gin.Context) {
|
||||
var req CreateAttributeDefinitionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
def, err := h.attrService.CreateDefinition(c.Request.Context(), service.CreateAttributeDefinitionInput{
|
||||
Key: req.Key,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Type: service.UserAttributeType(req.Type),
|
||||
Options: req.Options,
|
||||
Required: req.Required,
|
||||
Validation: req.Validation,
|
||||
Placeholder: req.Placeholder,
|
||||
Enabled: req.Enabled,
|
||||
})
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, defToResponse(def))
|
||||
}
|
||||
|
||||
// UpdateDefinition updates an attribute definition
|
||||
// PUT /admin/user-attributes/:id
|
||||
func (h *UserAttributeHandler) UpdateDefinition(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid attribute ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateAttributeDefinitionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
input := service.UpdateAttributeDefinitionInput{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Options: req.Options,
|
||||
Required: req.Required,
|
||||
Validation: req.Validation,
|
||||
Placeholder: req.Placeholder,
|
||||
Enabled: req.Enabled,
|
||||
}
|
||||
if req.Type != nil {
|
||||
t := service.UserAttributeType(*req.Type)
|
||||
input.Type = &t
|
||||
}
|
||||
|
||||
def, err := h.attrService.UpdateDefinition(c.Request.Context(), id, input)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, defToResponse(def))
|
||||
}
|
||||
|
||||
// DeleteDefinition deletes an attribute definition
|
||||
// DELETE /admin/user-attributes/:id
|
||||
func (h *UserAttributeHandler) DeleteDefinition(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid attribute ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.attrService.DeleteDefinition(c.Request.Context(), id); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Attribute definition deleted successfully"})
|
||||
}
|
||||
|
||||
// ReorderDefinitions reorders attribute definitions
|
||||
// PUT /admin/user-attributes/reorder
|
||||
func (h *UserAttributeHandler) ReorderDefinitions(c *gin.Context) {
|
||||
var req ReorderRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Convert IDs array to orders map (position in array = display_order)
|
||||
orders := make(map[int64]int, len(req.IDs))
|
||||
for i, id := range req.IDs {
|
||||
orders[id] = i
|
||||
}
|
||||
|
||||
if err := h.attrService.ReorderDefinitions(c.Request.Context(), orders); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Reorder successful"})
|
||||
}
|
||||
|
||||
// GetUserAttributes gets a user's attribute values
|
||||
// GET /admin/users/:id/attributes
|
||||
func (h *UserAttributeHandler) GetUserAttributes(c *gin.Context) {
|
||||
userID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid user ID")
|
||||
return
|
||||
}
|
||||
|
||||
values, err := h.attrService.GetUserAttributes(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]*AttributeValueResponse, 0, len(values))
|
||||
for i := range values {
|
||||
out = append(out, valueToResponse(&values[i]))
|
||||
}
|
||||
|
||||
response.Success(c, out)
|
||||
}
|
||||
|
||||
// UpdateUserAttributes updates a user's attribute values
|
||||
// PUT /admin/users/:id/attributes
|
||||
func (h *UserAttributeHandler) UpdateUserAttributes(c *gin.Context) {
|
||||
userID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid user ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateUserAttributesRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
inputs := make([]service.UpdateUserAttributeInput, 0, len(req.Values))
|
||||
for attrID, value := range req.Values {
|
||||
inputs = append(inputs, service.UpdateUserAttributeInput{
|
||||
AttributeID: attrID,
|
||||
Value: value,
|
||||
})
|
||||
}
|
||||
|
||||
if err := h.attrService.UpdateUserAttributes(c.Request.Context(), userID, inputs); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Return updated values
|
||||
values, err := h.attrService.GetUserAttributes(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]*AttributeValueResponse, 0, len(values))
|
||||
for i := range values {
|
||||
out = append(out, valueToResponse(&values[i]))
|
||||
}
|
||||
|
||||
response.Success(c, out)
|
||||
}
|
||||
|
||||
// GetBatchUserAttributes gets attribute values for multiple users
|
||||
// POST /admin/user-attributes/batch
|
||||
func (h *UserAttributeHandler) GetBatchUserAttributes(c *gin.Context) {
|
||||
var req BatchGetUserAttributesRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.UserIDs) == 0 {
|
||||
response.Success(c, BatchUserAttributesResponse{Attributes: map[int64]map[int64]string{}})
|
||||
return
|
||||
}
|
||||
|
||||
attrs, err := h.attrService.GetBatchUserAttributes(c.Request.Context(), req.UserIDs)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, BatchUserAttributesResponse{Attributes: attrs})
|
||||
}
|
||||
@@ -27,7 +27,6 @@ type CreateUserRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Username string `json:"username"`
|
||||
Wechat string `json:"wechat"`
|
||||
Notes string `json:"notes"`
|
||||
Balance float64 `json:"balance"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
@@ -40,7 +39,6 @@ type UpdateUserRequest struct {
|
||||
Email string `json:"email" binding:"omitempty,email"`
|
||||
Password string `json:"password" binding:"omitempty,min=6"`
|
||||
Username *string `json:"username"`
|
||||
Wechat *string `json:"wechat"`
|
||||
Notes *string `json:"notes"`
|
||||
Balance *float64 `json:"balance"`
|
||||
Concurrency *int `json:"concurrency"`
|
||||
@@ -57,13 +55,22 @@ type UpdateBalanceRequest struct {
|
||||
|
||||
// List handles listing all users with pagination
|
||||
// GET /api/v1/admin/users
|
||||
// Query params:
|
||||
// - status: filter by user status
|
||||
// - role: filter by user role
|
||||
// - search: search in email, username
|
||||
// - attr[{id}]: filter by custom attribute value, e.g. attr[1]=company
|
||||
func (h *UserHandler) List(c *gin.Context) {
|
||||
page, pageSize := response.ParsePagination(c)
|
||||
status := c.Query("status")
|
||||
role := c.Query("role")
|
||||
search := c.Query("search")
|
||||
|
||||
users, total, err := h.adminService.ListUsers(c.Request.Context(), page, pageSize, status, role, search)
|
||||
filters := service.UserListFilters{
|
||||
Status: c.Query("status"),
|
||||
Role: c.Query("role"),
|
||||
Search: c.Query("search"),
|
||||
Attributes: parseAttributeFilters(c),
|
||||
}
|
||||
|
||||
users, total, err := h.adminService.ListUsers(c.Request.Context(), page, pageSize, filters)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
@@ -76,6 +83,29 @@ func (h *UserHandler) List(c *gin.Context) {
|
||||
response.Paginated(c, out, total, page, pageSize)
|
||||
}
|
||||
|
||||
// parseAttributeFilters extracts attribute filters from query params
|
||||
// Format: attr[{attributeID}]=value, e.g. attr[1]=company&attr[2]=developer
|
||||
func parseAttributeFilters(c *gin.Context) map[int64]string {
|
||||
result := make(map[int64]string)
|
||||
|
||||
// Get all query params and look for attr[*] pattern
|
||||
for key, values := range c.Request.URL.Query() {
|
||||
if len(values) == 0 || values[0] == "" {
|
||||
continue
|
||||
}
|
||||
// Check if key matches pattern attr[{id}]
|
||||
if len(key) > 5 && key[:5] == "attr[" && key[len(key)-1] == ']' {
|
||||
idStr := key[5 : len(key)-1]
|
||||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err == nil && id > 0 {
|
||||
result[id] = values[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetByID handles getting a user by ID
|
||||
// GET /api/v1/admin/users/:id
|
||||
func (h *UserHandler) GetByID(c *gin.Context) {
|
||||
@@ -107,7 +137,6 @@ func (h *UserHandler) Create(c *gin.Context) {
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
Username: req.Username,
|
||||
Wechat: req.Wechat,
|
||||
Notes: req.Notes,
|
||||
Balance: req.Balance,
|
||||
Concurrency: req.Concurrency,
|
||||
@@ -141,7 +170,6 @@ func (h *UserHandler) Update(c *gin.Context) {
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
Username: req.Username,
|
||||
Wechat: req.Wechat,
|
||||
Notes: req.Notes,
|
||||
Balance: req.Balance,
|
||||
Concurrency: req.Concurrency,
|
||||
|
||||
@@ -10,7 +10,6 @@ func UserFromServiceShallow(u *service.User) *User {
|
||||
ID: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
Wechat: u.Wechat,
|
||||
Notes: u.Notes,
|
||||
Role: u.Role,
|
||||
Balance: u.Balance,
|
||||
|
||||
@@ -6,7 +6,6 @@ type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Wechat string `json:"wechat"`
|
||||
Notes string `json:"notes"`
|
||||
Role string `json:"role"`
|
||||
Balance float64 `json:"balance"`
|
||||
|
||||
@@ -20,6 +20,7 @@ type AdminHandlers struct {
|
||||
System *admin.SystemHandler
|
||||
Subscription *admin.SubscriptionHandler
|
||||
Usage *admin.UsageHandler
|
||||
UserAttribute *admin.UserAttributeHandler
|
||||
}
|
||||
|
||||
// Handlers contains all HTTP handlers
|
||||
|
||||
@@ -30,7 +30,6 @@ type ChangePasswordRequest struct {
|
||||
// UpdateProfileRequest represents the update profile request payload
|
||||
type UpdateProfileRequest struct {
|
||||
Username *string `json:"username"`
|
||||
Wechat *string `json:"wechat"`
|
||||
}
|
||||
|
||||
// GetProfile handles getting user profile
|
||||
@@ -99,7 +98,6 @@ func (h *UserHandler) UpdateProfile(c *gin.Context) {
|
||||
|
||||
svcReq := service.UpdateProfileRequest{
|
||||
Username: req.Username,
|
||||
Wechat: req.Wechat,
|
||||
}
|
||||
updatedUser, err := h.userService.UpdateProfile(c.Request.Context(), subject.UserID, svcReq)
|
||||
if err != nil {
|
||||
|
||||
@@ -23,6 +23,7 @@ func ProvideAdminHandlers(
|
||||
systemHandler *admin.SystemHandler,
|
||||
subscriptionHandler *admin.SubscriptionHandler,
|
||||
usageHandler *admin.UsageHandler,
|
||||
userAttributeHandler *admin.UserAttributeHandler,
|
||||
) *AdminHandlers {
|
||||
return &AdminHandlers{
|
||||
Dashboard: dashboardHandler,
|
||||
@@ -39,6 +40,7 @@ func ProvideAdminHandlers(
|
||||
System: systemHandler,
|
||||
Subscription: subscriptionHandler,
|
||||
Usage: usageHandler,
|
||||
UserAttribute: userAttributeHandler,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +109,7 @@ var ProviderSet = wire.NewSet(
|
||||
ProvideSystemHandler,
|
||||
admin.NewSubscriptionHandler,
|
||||
admin.NewUsageHandler,
|
||||
admin.NewUserAttributeHandler,
|
||||
|
||||
// AdminHandlers and Handlers constructors
|
||||
ProvideAdminHandlers,
|
||||
|
||||
@@ -294,7 +294,6 @@ func userEntityToService(u *dbent.User) *service.User {
|
||||
ID: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
Wechat: u.Wechat,
|
||||
Notes: u.Notes,
|
||||
PasswordHash: u.PasswordHash,
|
||||
Role: u.Role,
|
||||
|
||||
@@ -40,7 +40,6 @@ func mustCreateUser(t *testing.T, client *dbent.Client, u *service.User) *servic
|
||||
SetBalance(u.Balance).
|
||||
SetConcurrency(u.Concurrency).
|
||||
SetUsername(u.Username).
|
||||
SetWechat(u.Wechat).
|
||||
SetNotes(u.Notes)
|
||||
if !u.CreatedAt.IsZero() {
|
||||
create.SetCreatedAt(u.CreatedAt)
|
||||
|
||||
@@ -23,7 +23,6 @@ func TestMigrationsRunner_IsIdempotent_AndSchemaIsUpToDate(t *testing.T) {
|
||||
|
||||
// users: columns required by repository queries
|
||||
requireColumn(t, tx, "users", "username", "character varying", 100, false)
|
||||
requireColumn(t, tx, "users", "wechat", "character varying", 100, false)
|
||||
requireColumn(t, tx, "users", "notes", "text", 0, false)
|
||||
|
||||
// accounts: schedulable and rate-limit fields
|
||||
|
||||
385
backend/internal/repository/user_attribute_repo.go
Normal file
385
backend/internal/repository/user_attribute_repo.go
Normal file
@@ -0,0 +1,385 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
|
||||
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
// UserAttributeDefinitionRepository implementation
|
||||
type userAttributeDefinitionRepository struct {
|
||||
client *dbent.Client
|
||||
}
|
||||
|
||||
// NewUserAttributeDefinitionRepository creates a new repository instance
|
||||
func NewUserAttributeDefinitionRepository(client *dbent.Client) service.UserAttributeDefinitionRepository {
|
||||
return &userAttributeDefinitionRepository{client: client}
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) Create(ctx context.Context, def *service.UserAttributeDefinition) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
created, err := client.UserAttributeDefinition.Create().
|
||||
SetKey(def.Key).
|
||||
SetName(def.Name).
|
||||
SetDescription(def.Description).
|
||||
SetType(string(def.Type)).
|
||||
SetOptions(toEntOptions(def.Options)).
|
||||
SetRequired(def.Required).
|
||||
SetValidation(toEntValidation(def.Validation)).
|
||||
SetPlaceholder(def.Placeholder).
|
||||
SetEnabled(def.Enabled).
|
||||
Save(ctx)
|
||||
|
||||
if err != nil {
|
||||
return translatePersistenceError(err, nil, service.ErrAttributeKeyExists)
|
||||
}
|
||||
|
||||
def.ID = created.ID
|
||||
def.DisplayOrder = created.DisplayOrder
|
||||
def.CreatedAt = created.CreatedAt
|
||||
def.UpdatedAt = created.UpdatedAt
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) GetByID(ctx context.Context, id int64) (*service.UserAttributeDefinition, error) {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
e, err := client.UserAttributeDefinition.Query().
|
||||
Where(userattributedefinition.IDEQ(id)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, translatePersistenceError(err, service.ErrAttributeDefinitionNotFound, nil)
|
||||
}
|
||||
return defEntityToService(e), nil
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) GetByKey(ctx context.Context, key string) (*service.UserAttributeDefinition, error) {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
e, err := client.UserAttributeDefinition.Query().
|
||||
Where(userattributedefinition.KeyEQ(key)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, translatePersistenceError(err, service.ErrAttributeDefinitionNotFound, nil)
|
||||
}
|
||||
return defEntityToService(e), nil
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) Update(ctx context.Context, def *service.UserAttributeDefinition) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
updated, err := client.UserAttributeDefinition.UpdateOneID(def.ID).
|
||||
SetName(def.Name).
|
||||
SetDescription(def.Description).
|
||||
SetType(string(def.Type)).
|
||||
SetOptions(toEntOptions(def.Options)).
|
||||
SetRequired(def.Required).
|
||||
SetValidation(toEntValidation(def.Validation)).
|
||||
SetPlaceholder(def.Placeholder).
|
||||
SetDisplayOrder(def.DisplayOrder).
|
||||
SetEnabled(def.Enabled).
|
||||
Save(ctx)
|
||||
|
||||
if err != nil {
|
||||
return translatePersistenceError(err, service.ErrAttributeDefinitionNotFound, service.ErrAttributeKeyExists)
|
||||
}
|
||||
|
||||
def.UpdatedAt = updated.UpdatedAt
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) Delete(ctx context.Context, id int64) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
_, err := client.UserAttributeDefinition.Delete().
|
||||
Where(userattributedefinition.IDEQ(id)).
|
||||
Exec(ctx)
|
||||
return translatePersistenceError(err, service.ErrAttributeDefinitionNotFound, nil)
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) List(ctx context.Context, enabledOnly bool) ([]service.UserAttributeDefinition, error) {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
q := client.UserAttributeDefinition.Query()
|
||||
if enabledOnly {
|
||||
q = q.Where(userattributedefinition.EnabledEQ(true))
|
||||
}
|
||||
|
||||
entities, err := q.Order(dbent.Asc(userattributedefinition.FieldDisplayOrder)).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]service.UserAttributeDefinition, 0, len(entities))
|
||||
for _, e := range entities {
|
||||
result = append(result, *defEntityToService(e))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) UpdateDisplayOrders(ctx context.Context, orders map[int64]int) error {
|
||||
tx, err := r.client.Tx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
for id, order := range orders {
|
||||
if _, err := tx.UserAttributeDefinition.UpdateOneID(id).
|
||||
SetDisplayOrder(order).
|
||||
Save(ctx); err != nil {
|
||||
return translatePersistenceError(err, service.ErrAttributeDefinitionNotFound, nil)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (r *userAttributeDefinitionRepository) ExistsByKey(ctx context.Context, key string) (bool, error) {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
return client.UserAttributeDefinition.Query().
|
||||
Where(userattributedefinition.KeyEQ(key)).
|
||||
Exist(ctx)
|
||||
}
|
||||
|
||||
// UserAttributeValueRepository implementation
|
||||
type userAttributeValueRepository struct {
|
||||
client *dbent.Client
|
||||
}
|
||||
|
||||
// NewUserAttributeValueRepository creates a new repository instance
|
||||
func NewUserAttributeValueRepository(client *dbent.Client) service.UserAttributeValueRepository {
|
||||
return &userAttributeValueRepository{client: client}
|
||||
}
|
||||
|
||||
func (r *userAttributeValueRepository) GetByUserID(ctx context.Context, userID int64) ([]service.UserAttributeValue, error) {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
entities, err := client.UserAttributeValue.Query().
|
||||
Where(userattributevalue.UserIDEQ(userID)).
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]service.UserAttributeValue, 0, len(entities))
|
||||
for _, e := range entities {
|
||||
result = append(result, service.UserAttributeValue{
|
||||
ID: e.ID,
|
||||
UserID: e.UserID,
|
||||
AttributeID: e.AttributeID,
|
||||
Value: e.Value,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *userAttributeValueRepository) GetByUserIDs(ctx context.Context, userIDs []int64) ([]service.UserAttributeValue, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return []service.UserAttributeValue{}, nil
|
||||
}
|
||||
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
entities, err := client.UserAttributeValue.Query().
|
||||
Where(userattributevalue.UserIDIn(userIDs...)).
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]service.UserAttributeValue, 0, len(entities))
|
||||
for _, e := range entities {
|
||||
result = append(result, service.UserAttributeValue{
|
||||
ID: e.ID,
|
||||
UserID: e.UserID,
|
||||
AttributeID: e.AttributeID,
|
||||
Value: e.Value,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *userAttributeValueRepository) UpsertBatch(ctx context.Context, userID int64, inputs []service.UpdateUserAttributeInput) error {
|
||||
if len(inputs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := r.client.Tx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
for _, input := range inputs {
|
||||
// Use upsert (ON CONFLICT DO UPDATE)
|
||||
err := tx.UserAttributeValue.Create().
|
||||
SetUserID(userID).
|
||||
SetAttributeID(input.AttributeID).
|
||||
SetValue(input.Value).
|
||||
OnConflictColumns(userattributevalue.FieldUserID, userattributevalue.FieldAttributeID).
|
||||
UpdateValue().
|
||||
UpdateUpdatedAt().
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (r *userAttributeValueRepository) DeleteByAttributeID(ctx context.Context, attributeID int64) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
_, err := client.UserAttributeValue.Delete().
|
||||
Where(userattributevalue.AttributeIDEQ(attributeID)).
|
||||
Exec(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *userAttributeValueRepository) DeleteByUserID(ctx context.Context, userID int64) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
_, err := client.UserAttributeValue.Delete().
|
||||
Where(userattributevalue.UserIDEQ(userID)).
|
||||
Exec(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// Helper functions for entity to service conversion
|
||||
func defEntityToService(e *dbent.UserAttributeDefinition) *service.UserAttributeDefinition {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return &service.UserAttributeDefinition{
|
||||
ID: e.ID,
|
||||
Key: e.Key,
|
||||
Name: e.Name,
|
||||
Description: e.Description,
|
||||
Type: service.UserAttributeType(e.Type),
|
||||
Options: toServiceOptions(e.Options),
|
||||
Required: e.Required,
|
||||
Validation: toServiceValidation(e.Validation),
|
||||
Placeholder: e.Placeholder,
|
||||
DisplayOrder: e.DisplayOrder,
|
||||
Enabled: e.Enabled,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// Type conversion helpers (map types <-> service types)
|
||||
func toEntOptions(opts []service.UserAttributeOption) []map[string]any {
|
||||
if opts == nil {
|
||||
return []map[string]any{}
|
||||
}
|
||||
result := make([]map[string]any, len(opts))
|
||||
for i, o := range opts {
|
||||
result[i] = map[string]any{"value": o.Value, "label": o.Label}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toServiceOptions(opts []map[string]any) []service.UserAttributeOption {
|
||||
if opts == nil {
|
||||
return []service.UserAttributeOption{}
|
||||
}
|
||||
result := make([]service.UserAttributeOption, len(opts))
|
||||
for i, o := range opts {
|
||||
result[i] = service.UserAttributeOption{
|
||||
Value: getString(o, "value"),
|
||||
Label: getString(o, "label"),
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toEntValidation(v service.UserAttributeValidation) map[string]any {
|
||||
result := map[string]any{}
|
||||
if v.MinLength != nil {
|
||||
result["min_length"] = *v.MinLength
|
||||
}
|
||||
if v.MaxLength != nil {
|
||||
result["max_length"] = *v.MaxLength
|
||||
}
|
||||
if v.Min != nil {
|
||||
result["min"] = *v.Min
|
||||
}
|
||||
if v.Max != nil {
|
||||
result["max"] = *v.Max
|
||||
}
|
||||
if v.Pattern != nil {
|
||||
result["pattern"] = *v.Pattern
|
||||
}
|
||||
if v.Message != nil {
|
||||
result["message"] = *v.Message
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toServiceValidation(v map[string]any) service.UserAttributeValidation {
|
||||
result := service.UserAttributeValidation{}
|
||||
if val := getInt(v, "min_length"); val != nil {
|
||||
result.MinLength = val
|
||||
}
|
||||
if val := getInt(v, "max_length"); val != nil {
|
||||
result.MaxLength = val
|
||||
}
|
||||
if val := getInt(v, "min"); val != nil {
|
||||
result.Min = val
|
||||
}
|
||||
if val := getInt(v, "max"); val != nil {
|
||||
result.Max = val
|
||||
}
|
||||
if val := getStringPtr(v, "pattern"); val != nil {
|
||||
result.Pattern = val
|
||||
}
|
||||
if val := getStringPtr(v, "message"); val != nil {
|
||||
result.Message = val
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Helper functions for type conversion
|
||||
func getString(m map[string]any, key string) string {
|
||||
if v, ok := m[key]; ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getStringPtr(m map[string]any, key string) *string {
|
||||
if v, ok := m[key]; ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return &s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getInt(m map[string]any, key string) *int {
|
||||
if v, ok := m[key]; ok {
|
||||
switch n := v.(type) {
|
||||
case int:
|
||||
return &n
|
||||
case int64:
|
||||
i := int(n)
|
||||
return &i
|
||||
case float64:
|
||||
i := int(n)
|
||||
return &i
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
dbuser "github.com/Wei-Shaw/sub2api/ent/user"
|
||||
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
|
||||
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
|
||||
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -50,7 +51,6 @@ func (r *userRepository) Create(ctx context.Context, userIn *service.User) error
|
||||
created, err := txClient.User.Create().
|
||||
SetEmail(userIn.Email).
|
||||
SetUsername(userIn.Username).
|
||||
SetWechat(userIn.Wechat).
|
||||
SetNotes(userIn.Notes).
|
||||
SetPasswordHash(userIn.PasswordHash).
|
||||
SetRole(userIn.Role).
|
||||
@@ -133,7 +133,6 @@ func (r *userRepository) Update(ctx context.Context, userIn *service.User) error
|
||||
updated, err := txClient.User.UpdateOneID(userIn.ID).
|
||||
SetEmail(userIn.Email).
|
||||
SetUsername(userIn.Username).
|
||||
SetWechat(userIn.Wechat).
|
||||
SetNotes(userIn.Notes).
|
||||
SetPasswordHash(userIn.PasswordHash).
|
||||
SetRole(userIn.Role).
|
||||
@@ -171,28 +170,38 @@ func (r *userRepository) Delete(ctx context.Context, id int64) error {
|
||||
}
|
||||
|
||||
func (r *userRepository) List(ctx context.Context, params pagination.PaginationParams) ([]service.User, *pagination.PaginationResult, error) {
|
||||
return r.ListWithFilters(ctx, params, "", "", "")
|
||||
return r.ListWithFilters(ctx, params, service.UserListFilters{})
|
||||
}
|
||||
|
||||
func (r *userRepository) ListWithFilters(ctx context.Context, params pagination.PaginationParams, status, role, search string) ([]service.User, *pagination.PaginationResult, error) {
|
||||
func (r *userRepository) ListWithFilters(ctx context.Context, params pagination.PaginationParams, filters service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
|
||||
q := r.client.User.Query()
|
||||
|
||||
if status != "" {
|
||||
q = q.Where(dbuser.StatusEQ(status))
|
||||
if filters.Status != "" {
|
||||
q = q.Where(dbuser.StatusEQ(filters.Status))
|
||||
}
|
||||
if role != "" {
|
||||
q = q.Where(dbuser.RoleEQ(role))
|
||||
if filters.Role != "" {
|
||||
q = q.Where(dbuser.RoleEQ(filters.Role))
|
||||
}
|
||||
if search != "" {
|
||||
if filters.Search != "" {
|
||||
q = q.Where(
|
||||
dbuser.Or(
|
||||
dbuser.EmailContainsFold(search),
|
||||
dbuser.UsernameContainsFold(search),
|
||||
dbuser.WechatContainsFold(search),
|
||||
dbuser.EmailContainsFold(filters.Search),
|
||||
dbuser.UsernameContainsFold(filters.Search),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// If attribute filters are specified, we need to filter by user IDs first
|
||||
var allowedUserIDs []int64
|
||||
if len(filters.Attributes) > 0 {
|
||||
allowedUserIDs = r.filterUsersByAttributes(ctx, filters.Attributes)
|
||||
if len(allowedUserIDs) == 0 {
|
||||
// No users match the attribute filters
|
||||
return []service.User{}, paginationResultFromTotal(0, params), nil
|
||||
}
|
||||
q = q.Where(dbuser.IDIn(allowedUserIDs...))
|
||||
}
|
||||
|
||||
total, err := q.Clone().Count(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -252,6 +261,59 @@ func (r *userRepository) ListWithFilters(ctx context.Context, params pagination.
|
||||
return outUsers, paginationResultFromTotal(int64(total), params), nil
|
||||
}
|
||||
|
||||
// filterUsersByAttributes returns user IDs that match ALL the given attribute filters
|
||||
func (r *userRepository) filterUsersByAttributes(ctx context.Context, attrs map[int64]string) []int64 {
|
||||
if len(attrs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// For each attribute filter, get the set of matching user IDs
|
||||
// Then intersect all sets to get users matching ALL filters
|
||||
var resultSet map[int64]struct{}
|
||||
first := true
|
||||
|
||||
for attrID, value := range attrs {
|
||||
// Query user_attribute_values for this attribute
|
||||
values, err := r.client.UserAttributeValue.Query().
|
||||
Where(
|
||||
userattributevalue.AttributeIDEQ(attrID),
|
||||
userattributevalue.ValueContainsFold(value),
|
||||
).
|
||||
All(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
currentSet := make(map[int64]struct{}, len(values))
|
||||
for _, v := range values {
|
||||
currentSet[v.UserID] = struct{}{}
|
||||
}
|
||||
|
||||
if first {
|
||||
resultSet = currentSet
|
||||
first = false
|
||||
} else {
|
||||
// Intersect with previous results
|
||||
for userID := range resultSet {
|
||||
if _, ok := currentSet[userID]; !ok {
|
||||
delete(resultSet, userID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Early exit if no users match
|
||||
if len(resultSet) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]int64, 0, len(resultSet))
|
||||
for userID := range resultSet {
|
||||
result = append(result, userID)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *userRepository) UpdateBalance(ctx context.Context, id int64, amount float64) error {
|
||||
client := clientFromContext(ctx, r.client)
|
||||
n, err := client.User.Update().Where(dbuser.IDEQ(id)).AddBalance(amount).Save(ctx)
|
||||
|
||||
@@ -166,7 +166,7 @@ func (s *UserRepoSuite) TestListWithFilters_Status() {
|
||||
s.mustCreateUser(&service.User{Email: "active@test.com", Status: service.StatusActive})
|
||||
s.mustCreateUser(&service.User{Email: "disabled@test.com", Status: service.StatusDisabled})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.StatusActive, "", "")
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Status: service.StatusActive})
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(users, 1)
|
||||
s.Require().Equal(service.StatusActive, users[0].Status)
|
||||
@@ -176,7 +176,7 @@ func (s *UserRepoSuite) TestListWithFilters_Role() {
|
||||
s.mustCreateUser(&service.User{Email: "user@test.com", Role: service.RoleUser})
|
||||
s.mustCreateUser(&service.User{Email: "admin@test.com", Role: service.RoleAdmin})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", service.RoleAdmin, "")
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Role: service.RoleAdmin})
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(users, 1)
|
||||
s.Require().Equal(service.RoleAdmin, users[0].Role)
|
||||
@@ -186,7 +186,7 @@ func (s *UserRepoSuite) TestListWithFilters_Search() {
|
||||
s.mustCreateUser(&service.User{Email: "alice@test.com", Username: "Alice"})
|
||||
s.mustCreateUser(&service.User{Email: "bob@test.com", Username: "Bob"})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "alice")
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Search: "alice"})
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(users, 1)
|
||||
s.Require().Contains(users[0].Email, "alice")
|
||||
@@ -196,22 +196,12 @@ func (s *UserRepoSuite) TestListWithFilters_SearchByUsername() {
|
||||
s.mustCreateUser(&service.User{Email: "u1@test.com", Username: "JohnDoe"})
|
||||
s.mustCreateUser(&service.User{Email: "u2@test.com", Username: "JaneSmith"})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "john")
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Search: "john"})
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(users, 1)
|
||||
s.Require().Equal("JohnDoe", users[0].Username)
|
||||
}
|
||||
|
||||
func (s *UserRepoSuite) TestListWithFilters_SearchByWechat() {
|
||||
s.mustCreateUser(&service.User{Email: "w1@test.com", Wechat: "wx_hello"})
|
||||
s.mustCreateUser(&service.User{Email: "w2@test.com", Wechat: "wx_world"})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "wx_hello")
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(users, 1)
|
||||
s.Require().Equal("wx_hello", users[0].Wechat)
|
||||
}
|
||||
|
||||
func (s *UserRepoSuite) TestListWithFilters_LoadsActiveSubscriptions() {
|
||||
user := s.mustCreateUser(&service.User{Email: "sub@test.com", Status: service.StatusActive})
|
||||
groupActive := s.mustCreateGroup("g-sub-active")
|
||||
@@ -226,7 +216,7 @@ func (s *UserRepoSuite) TestListWithFilters_LoadsActiveSubscriptions() {
|
||||
c.SetExpiresAt(time.Now().Add(-1 * time.Hour))
|
||||
})
|
||||
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "sub@")
|
||||
users, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Search: "sub@"})
|
||||
s.Require().NoError(err, "ListWithFilters")
|
||||
s.Require().Len(users, 1, "expected 1 user")
|
||||
s.Require().Len(users[0].Subscriptions, 1, "expected 1 active subscription")
|
||||
@@ -238,7 +228,6 @@ func (s *UserRepoSuite) TestListWithFilters_CombinedFilters() {
|
||||
s.mustCreateUser(&service.User{
|
||||
Email: "a@example.com",
|
||||
Username: "Alice",
|
||||
Wechat: "wx_a",
|
||||
Role: service.RoleUser,
|
||||
Status: service.StatusActive,
|
||||
Balance: 10,
|
||||
@@ -246,7 +235,6 @@ func (s *UserRepoSuite) TestListWithFilters_CombinedFilters() {
|
||||
target := s.mustCreateUser(&service.User{
|
||||
Email: "b@example.com",
|
||||
Username: "Bob",
|
||||
Wechat: "wx_b",
|
||||
Role: service.RoleAdmin,
|
||||
Status: service.StatusActive,
|
||||
Balance: 1,
|
||||
@@ -257,7 +245,7 @@ func (s *UserRepoSuite) TestListWithFilters_CombinedFilters() {
|
||||
Status: service.StatusDisabled,
|
||||
})
|
||||
|
||||
users, page, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.StatusActive, service.RoleAdmin, "b@")
|
||||
users, page, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, service.UserListFilters{Status: service.StatusActive, Role: service.RoleAdmin, Search: "b@"})
|
||||
s.Require().NoError(err, "ListWithFilters")
|
||||
s.Require().Equal(int64(1), page.Total, "ListWithFilters total mismatch")
|
||||
s.Require().Len(users, 1, "ListWithFilters len mismatch")
|
||||
@@ -448,7 +436,6 @@ func (s *UserRepoSuite) TestCRUD_And_Filters_And_AtomicUpdates() {
|
||||
user1 := s.mustCreateUser(&service.User{
|
||||
Email: "a@example.com",
|
||||
Username: "Alice",
|
||||
Wechat: "wx_a",
|
||||
Role: service.RoleUser,
|
||||
Status: service.StatusActive,
|
||||
Balance: 10,
|
||||
@@ -456,7 +443,6 @@ func (s *UserRepoSuite) TestCRUD_And_Filters_And_AtomicUpdates() {
|
||||
user2 := s.mustCreateUser(&service.User{
|
||||
Email: "b@example.com",
|
||||
Username: "Bob",
|
||||
Wechat: "wx_b",
|
||||
Role: service.RoleAdmin,
|
||||
Status: service.StatusActive,
|
||||
Balance: 1,
|
||||
@@ -501,7 +487,7 @@ func (s *UserRepoSuite) TestCRUD_And_Filters_And_AtomicUpdates() {
|
||||
s.Require().Equal(user1.Concurrency+3, got5.Concurrency)
|
||||
|
||||
params := pagination.PaginationParams{Page: 1, PageSize: 10}
|
||||
users, page, err := s.repo.ListWithFilters(s.ctx, params, service.StatusActive, service.RoleAdmin, "b@")
|
||||
users, page, err := s.repo.ListWithFilters(s.ctx, params, service.UserListFilters{Status: service.StatusActive, Role: service.RoleAdmin, Search: "b@"})
|
||||
s.Require().NoError(err, "ListWithFilters")
|
||||
s.Require().Equal(int64(1), page.Total, "ListWithFilters total mismatch")
|
||||
s.Require().Len(users, 1, "ListWithFilters len mismatch")
|
||||
|
||||
@@ -36,6 +36,8 @@ var ProviderSet = wire.NewSet(
|
||||
NewUsageLogRepository,
|
||||
NewSettingRepository,
|
||||
NewUserSubscriptionRepository,
|
||||
NewUserAttributeDefinitionRepository,
|
||||
NewUserAttributeValueRepository,
|
||||
|
||||
// Cache implementations
|
||||
NewGatewayCache,
|
||||
|
||||
@@ -51,7 +51,6 @@ func TestAPIContracts(t *testing.T) {
|
||||
"id": 1,
|
||||
"email": "alice@example.com",
|
||||
"username": "alice",
|
||||
"wechat": "wx_alice",
|
||||
"notes": "hello",
|
||||
"role": "user",
|
||||
"balance": 12.5,
|
||||
@@ -348,7 +347,6 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
ID: 1,
|
||||
Email: "alice@example.com",
|
||||
Username: "alice",
|
||||
Wechat: "wx_alice",
|
||||
Notes: "hello",
|
||||
Role: service.RoleUser,
|
||||
Balance: 12.5,
|
||||
@@ -503,7 +501,7 @@ func (r *stubUserRepo) List(ctx context.Context, params pagination.PaginationPar
|
||||
return nil, nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (r *stubUserRepo) ListWithFilters(ctx context.Context, params pagination.PaginationParams, status, role, search string) ([]service.User, *pagination.PaginationResult, error) {
|
||||
func (r *stubUserRepo) ListWithFilters(ctx context.Context, params pagination.PaginationParams, filters service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
|
||||
return nil, nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ func RegisterAdminRoutes(
|
||||
|
||||
// 使用记录管理
|
||||
registerUsageRoutes(admin, h)
|
||||
|
||||
// 用户属性管理
|
||||
registerUserAttributeRoutes(admin, h)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +85,10 @@ func registerUserManagementRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
|
||||
users.POST("/:id/balance", h.Admin.User.UpdateBalance)
|
||||
users.GET("/:id/api-keys", h.Admin.User.GetUserAPIKeys)
|
||||
users.GET("/:id/usage", h.Admin.User.GetUserUsage)
|
||||
|
||||
// User attribute values
|
||||
users.GET("/:id/attributes", h.Admin.UserAttribute.GetUserAttributes)
|
||||
users.PUT("/:id/attributes", h.Admin.UserAttribute.UpdateUserAttributes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,3 +251,15 @@ func registerUsageRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
|
||||
usage.GET("/search-api-keys", h.Admin.Usage.SearchApiKeys)
|
||||
}
|
||||
}
|
||||
|
||||
func registerUserAttributeRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
|
||||
attrs := admin.Group("/user-attributes")
|
||||
{
|
||||
attrs.GET("", h.Admin.UserAttribute.ListDefinitions)
|
||||
attrs.POST("", h.Admin.UserAttribute.CreateDefinition)
|
||||
attrs.POST("/batch", h.Admin.UserAttribute.GetBatchUserAttributes)
|
||||
attrs.PUT("/reorder", h.Admin.UserAttribute.ReorderDefinitions)
|
||||
attrs.PUT("/:id", h.Admin.UserAttribute.UpdateDefinition)
|
||||
attrs.DELETE("/:id", h.Admin.UserAttribute.DeleteDefinition)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
// AdminService interface defines admin management operations
|
||||
type AdminService interface {
|
||||
// User management
|
||||
ListUsers(ctx context.Context, page, pageSize int, status, role, search string) ([]User, int64, error)
|
||||
ListUsers(ctx context.Context, page, pageSize int, filters UserListFilters) ([]User, int64, error)
|
||||
GetUser(ctx context.Context, id int64) (*User, error)
|
||||
CreateUser(ctx context.Context, input *CreateUserInput) (*User, error)
|
||||
UpdateUser(ctx context.Context, id int64, input *UpdateUserInput) (*User, error)
|
||||
@@ -70,7 +70,6 @@ type CreateUserInput struct {
|
||||
Email string
|
||||
Password string
|
||||
Username string
|
||||
Wechat string
|
||||
Notes string
|
||||
Balance float64
|
||||
Concurrency int
|
||||
@@ -81,7 +80,6 @@ type UpdateUserInput struct {
|
||||
Email string
|
||||
Password string
|
||||
Username *string
|
||||
Wechat *string
|
||||
Notes *string
|
||||
Balance *float64 // 使用指针区分"未提供"和"设置为0"
|
||||
Concurrency *int // 使用指针区分"未提供"和"设置为0"
|
||||
@@ -252,9 +250,9 @@ func NewAdminService(
|
||||
}
|
||||
|
||||
// User management implementations
|
||||
func (s *adminServiceImpl) ListUsers(ctx context.Context, page, pageSize int, status, role, search string) ([]User, int64, error) {
|
||||
func (s *adminServiceImpl) ListUsers(ctx context.Context, page, pageSize int, filters UserListFilters) ([]User, int64, error) {
|
||||
params := pagination.PaginationParams{Page: page, PageSize: pageSize}
|
||||
users, result, err := s.userRepo.ListWithFilters(ctx, params, status, role, search)
|
||||
users, result, err := s.userRepo.ListWithFilters(ctx, params, filters)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -269,7 +267,6 @@ func (s *adminServiceImpl) CreateUser(ctx context.Context, input *CreateUserInpu
|
||||
user := &User{
|
||||
Email: input.Email,
|
||||
Username: input.Username,
|
||||
Wechat: input.Wechat,
|
||||
Notes: input.Notes,
|
||||
Role: RoleUser, // Always create as regular user, never admin
|
||||
Balance: input.Balance,
|
||||
@@ -311,9 +308,6 @@ func (s *adminServiceImpl) UpdateUser(ctx context.Context, id int64, input *Upda
|
||||
if input.Username != nil {
|
||||
user.Username = *input.Username
|
||||
}
|
||||
if input.Wechat != nil {
|
||||
user.Wechat = *input.Wechat
|
||||
}
|
||||
if input.Notes != nil {
|
||||
user.Notes = *input.Notes
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ func TestAdminService_CreateUser_Success(t *testing.T) {
|
||||
Email: "user@test.com",
|
||||
Password: "strong-pass",
|
||||
Username: "tester",
|
||||
Wechat: "wx",
|
||||
Notes: "note",
|
||||
Balance: 12.5,
|
||||
Concurrency: 7,
|
||||
@@ -31,7 +30,6 @@ func TestAdminService_CreateUser_Success(t *testing.T) {
|
||||
require.Equal(t, int64(10), user.ID)
|
||||
require.Equal(t, input.Email, user.Email)
|
||||
require.Equal(t, input.Username, user.Username)
|
||||
require.Equal(t, input.Wechat, user.Wechat)
|
||||
require.Equal(t, input.Notes, user.Notes)
|
||||
require.Equal(t, input.Balance, user.Balance)
|
||||
require.Equal(t, input.Concurrency, user.Concurrency)
|
||||
|
||||
@@ -66,7 +66,7 @@ func (s *userRepoStub) List(ctx context.Context, params pagination.PaginationPar
|
||||
panic("unexpected List call")
|
||||
}
|
||||
|
||||
func (s *userRepoStub) ListWithFilters(ctx context.Context, params pagination.PaginationParams, status, role, search string) ([]User, *pagination.PaginationResult, error) {
|
||||
func (s *userRepoStub) ListWithFilters(ctx context.Context, params pagination.PaginationParams, filters UserListFilters) ([]User, *pagination.PaginationResult, error) {
|
||||
panic("unexpected ListWithFilters call")
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ type User struct {
|
||||
ID int64
|
||||
Email string
|
||||
Username string
|
||||
Wechat string
|
||||
Notes string
|
||||
PasswordHash string
|
||||
Role string
|
||||
|
||||
125
backend/internal/service/user_attribute.go
Normal file
125
backend/internal/service/user_attribute.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// Error definitions for user attribute operations
|
||||
var (
|
||||
ErrAttributeDefinitionNotFound = infraerrors.NotFound("ATTRIBUTE_DEFINITION_NOT_FOUND", "attribute definition not found")
|
||||
ErrAttributeKeyExists = infraerrors.Conflict("ATTRIBUTE_KEY_EXISTS", "attribute key already exists")
|
||||
ErrInvalidAttributeType = infraerrors.BadRequest("INVALID_ATTRIBUTE_TYPE", "invalid attribute type")
|
||||
ErrAttributeValidationFailed = infraerrors.BadRequest("ATTRIBUTE_VALIDATION_FAILED", "attribute value validation failed")
|
||||
)
|
||||
|
||||
// UserAttributeType represents supported attribute types
|
||||
type UserAttributeType string
|
||||
|
||||
const (
|
||||
AttributeTypeText UserAttributeType = "text"
|
||||
AttributeTypeTextarea UserAttributeType = "textarea"
|
||||
AttributeTypeNumber UserAttributeType = "number"
|
||||
AttributeTypeEmail UserAttributeType = "email"
|
||||
AttributeTypeURL UserAttributeType = "url"
|
||||
AttributeTypeDate UserAttributeType = "date"
|
||||
AttributeTypeSelect UserAttributeType = "select"
|
||||
AttributeTypeMultiSelect UserAttributeType = "multi_select"
|
||||
)
|
||||
|
||||
// UserAttributeOption represents a select option for select/multi_select types
|
||||
type UserAttributeOption struct {
|
||||
Value string `json:"value"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// UserAttributeValidation represents validation rules for an attribute
|
||||
type UserAttributeValidation struct {
|
||||
MinLength *int `json:"min_length,omitempty"`
|
||||
MaxLength *int `json:"max_length,omitempty"`
|
||||
Min *int `json:"min,omitempty"`
|
||||
Max *int `json:"max,omitempty"`
|
||||
Pattern *string `json:"pattern,omitempty"`
|
||||
Message *string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// UserAttributeDefinition represents a custom attribute definition
|
||||
type UserAttributeDefinition struct {
|
||||
ID int64
|
||||
Key string
|
||||
Name string
|
||||
Description string
|
||||
Type UserAttributeType
|
||||
Options []UserAttributeOption
|
||||
Required bool
|
||||
Validation UserAttributeValidation
|
||||
Placeholder string
|
||||
DisplayOrder int
|
||||
Enabled bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// UserAttributeValue represents a user's attribute value
|
||||
type UserAttributeValue struct {
|
||||
ID int64
|
||||
UserID int64
|
||||
AttributeID int64
|
||||
Value string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CreateAttributeDefinitionInput for creating new definition
|
||||
type CreateAttributeDefinitionInput struct {
|
||||
Key string
|
||||
Name string
|
||||
Description string
|
||||
Type UserAttributeType
|
||||
Options []UserAttributeOption
|
||||
Required bool
|
||||
Validation UserAttributeValidation
|
||||
Placeholder string
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// UpdateAttributeDefinitionInput for updating definition
|
||||
type UpdateAttributeDefinitionInput struct {
|
||||
Name *string
|
||||
Description *string
|
||||
Type *UserAttributeType
|
||||
Options *[]UserAttributeOption
|
||||
Required *bool
|
||||
Validation *UserAttributeValidation
|
||||
Placeholder *string
|
||||
Enabled *bool
|
||||
}
|
||||
|
||||
// UpdateUserAttributeInput for updating a single attribute value
|
||||
type UpdateUserAttributeInput struct {
|
||||
AttributeID int64
|
||||
Value string
|
||||
}
|
||||
|
||||
// UserAttributeDefinitionRepository interface for attribute definition persistence
|
||||
type UserAttributeDefinitionRepository interface {
|
||||
Create(ctx context.Context, def *UserAttributeDefinition) error
|
||||
GetByID(ctx context.Context, id int64) (*UserAttributeDefinition, error)
|
||||
GetByKey(ctx context.Context, key string) (*UserAttributeDefinition, error)
|
||||
Update(ctx context.Context, def *UserAttributeDefinition) error
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, enabledOnly bool) ([]UserAttributeDefinition, error)
|
||||
UpdateDisplayOrders(ctx context.Context, orders map[int64]int) error
|
||||
ExistsByKey(ctx context.Context, key string) (bool, error)
|
||||
}
|
||||
|
||||
// UserAttributeValueRepository interface for user attribute value persistence
|
||||
type UserAttributeValueRepository interface {
|
||||
GetByUserID(ctx context.Context, userID int64) ([]UserAttributeValue, error)
|
||||
GetByUserIDs(ctx context.Context, userIDs []int64) ([]UserAttributeValue, error)
|
||||
UpsertBatch(ctx context.Context, userID int64, values []UpdateUserAttributeInput) error
|
||||
DeleteByAttributeID(ctx context.Context, attributeID int64) error
|
||||
DeleteByUserID(ctx context.Context, userID int64) error
|
||||
}
|
||||
295
backend/internal/service/user_attribute_service.go
Normal file
295
backend/internal/service/user_attribute_service.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// UserAttributeService handles attribute management
|
||||
type UserAttributeService struct {
|
||||
defRepo UserAttributeDefinitionRepository
|
||||
valueRepo UserAttributeValueRepository
|
||||
}
|
||||
|
||||
// NewUserAttributeService creates a new service instance
|
||||
func NewUserAttributeService(
|
||||
defRepo UserAttributeDefinitionRepository,
|
||||
valueRepo UserAttributeValueRepository,
|
||||
) *UserAttributeService {
|
||||
return &UserAttributeService{
|
||||
defRepo: defRepo,
|
||||
valueRepo: valueRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateDefinition creates a new attribute definition
|
||||
func (s *UserAttributeService) CreateDefinition(ctx context.Context, input CreateAttributeDefinitionInput) (*UserAttributeDefinition, error) {
|
||||
// Validate type
|
||||
if !isValidAttributeType(input.Type) {
|
||||
return nil, ErrInvalidAttributeType
|
||||
}
|
||||
|
||||
// Check if key exists
|
||||
exists, err := s.defRepo.ExistsByKey(ctx, input.Key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("check key exists: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, ErrAttributeKeyExists
|
||||
}
|
||||
|
||||
def := &UserAttributeDefinition{
|
||||
Key: input.Key,
|
||||
Name: input.Name,
|
||||
Description: input.Description,
|
||||
Type: input.Type,
|
||||
Options: input.Options,
|
||||
Required: input.Required,
|
||||
Validation: input.Validation,
|
||||
Placeholder: input.Placeholder,
|
||||
Enabled: input.Enabled,
|
||||
}
|
||||
|
||||
if err := s.defRepo.Create(ctx, def); err != nil {
|
||||
return nil, fmt.Errorf("create definition: %w", err)
|
||||
}
|
||||
|
||||
return def, nil
|
||||
}
|
||||
|
||||
// GetDefinition retrieves a definition by ID
|
||||
func (s *UserAttributeService) GetDefinition(ctx context.Context, id int64) (*UserAttributeDefinition, error) {
|
||||
return s.defRepo.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// ListDefinitions lists all definitions
|
||||
func (s *UserAttributeService) ListDefinitions(ctx context.Context, enabledOnly bool) ([]UserAttributeDefinition, error) {
|
||||
return s.defRepo.List(ctx, enabledOnly)
|
||||
}
|
||||
|
||||
// UpdateDefinition updates an existing definition
|
||||
func (s *UserAttributeService) UpdateDefinition(ctx context.Context, id int64, input UpdateAttributeDefinitionInput) (*UserAttributeDefinition, error) {
|
||||
def, err := s.defRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if input.Name != nil {
|
||||
def.Name = *input.Name
|
||||
}
|
||||
if input.Description != nil {
|
||||
def.Description = *input.Description
|
||||
}
|
||||
if input.Type != nil {
|
||||
if !isValidAttributeType(*input.Type) {
|
||||
return nil, ErrInvalidAttributeType
|
||||
}
|
||||
def.Type = *input.Type
|
||||
}
|
||||
if input.Options != nil {
|
||||
def.Options = *input.Options
|
||||
}
|
||||
if input.Required != nil {
|
||||
def.Required = *input.Required
|
||||
}
|
||||
if input.Validation != nil {
|
||||
def.Validation = *input.Validation
|
||||
}
|
||||
if input.Placeholder != nil {
|
||||
def.Placeholder = *input.Placeholder
|
||||
}
|
||||
if input.Enabled != nil {
|
||||
def.Enabled = *input.Enabled
|
||||
}
|
||||
|
||||
if err := s.defRepo.Update(ctx, def); err != nil {
|
||||
return nil, fmt.Errorf("update definition: %w", err)
|
||||
}
|
||||
|
||||
return def, nil
|
||||
}
|
||||
|
||||
// DeleteDefinition soft-deletes a definition and hard-deletes associated values
|
||||
func (s *UserAttributeService) DeleteDefinition(ctx context.Context, id int64) error {
|
||||
// Check if definition exists
|
||||
_, err := s.defRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// First delete all values (hard delete)
|
||||
if err := s.valueRepo.DeleteByAttributeID(ctx, id); err != nil {
|
||||
return fmt.Errorf("delete values: %w", err)
|
||||
}
|
||||
|
||||
// Then soft-delete the definition
|
||||
if err := s.defRepo.Delete(ctx, id); err != nil {
|
||||
return fmt.Errorf("delete definition: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReorderDefinitions updates display order for multiple definitions
|
||||
func (s *UserAttributeService) ReorderDefinitions(ctx context.Context, orders map[int64]int) error {
|
||||
return s.defRepo.UpdateDisplayOrders(ctx, orders)
|
||||
}
|
||||
|
||||
// GetUserAttributes retrieves all attribute values for a user
|
||||
func (s *UserAttributeService) GetUserAttributes(ctx context.Context, userID int64) ([]UserAttributeValue, error) {
|
||||
return s.valueRepo.GetByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// GetBatchUserAttributes retrieves attribute values for multiple users
|
||||
// Returns a map of userID -> map of attributeID -> value
|
||||
func (s *UserAttributeService) GetBatchUserAttributes(ctx context.Context, userIDs []int64) (map[int64]map[int64]string, error) {
|
||||
values, err := s.valueRepo.GetByUserIDs(ctx, userIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make(map[int64]map[int64]string)
|
||||
for _, v := range values {
|
||||
if result[v.UserID] == nil {
|
||||
result[v.UserID] = make(map[int64]string)
|
||||
}
|
||||
result[v.UserID][v.AttributeID] = v.Value
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// UpdateUserAttributes batch updates attribute values for a user
|
||||
func (s *UserAttributeService) UpdateUserAttributes(ctx context.Context, userID int64, inputs []UpdateUserAttributeInput) error {
|
||||
// Validate all values before updating
|
||||
defs, err := s.defRepo.List(ctx, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list definitions: %w", err)
|
||||
}
|
||||
|
||||
defMap := make(map[int64]*UserAttributeDefinition, len(defs))
|
||||
for i := range defs {
|
||||
defMap[defs[i].ID] = &defs[i]
|
||||
}
|
||||
|
||||
for _, input := range inputs {
|
||||
def, ok := defMap[input.AttributeID]
|
||||
if !ok {
|
||||
return ErrAttributeDefinitionNotFound
|
||||
}
|
||||
|
||||
if err := s.validateValue(def, input.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.valueRepo.UpsertBatch(ctx, userID, inputs)
|
||||
}
|
||||
|
||||
// validateValue validates a value against its definition
|
||||
func (s *UserAttributeService) validateValue(def *UserAttributeDefinition, value string) error {
|
||||
// Skip validation for empty non-required fields
|
||||
if value == "" && !def.Required {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Required check
|
||||
if def.Required && value == "" {
|
||||
return validationError(fmt.Sprintf("%s is required", def.Name))
|
||||
}
|
||||
|
||||
v := def.Validation
|
||||
|
||||
// String length validation
|
||||
if v.MinLength != nil && len(value) < *v.MinLength {
|
||||
return validationError(fmt.Sprintf("%s must be at least %d characters", def.Name, *v.MinLength))
|
||||
}
|
||||
if v.MaxLength != nil && len(value) > *v.MaxLength {
|
||||
return validationError(fmt.Sprintf("%s must be at most %d characters", def.Name, *v.MaxLength))
|
||||
}
|
||||
|
||||
// Number validation
|
||||
if def.Type == AttributeTypeNumber && value != "" {
|
||||
num, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return validationError(fmt.Sprintf("%s must be a number", def.Name))
|
||||
}
|
||||
if v.Min != nil && num < *v.Min {
|
||||
return validationError(fmt.Sprintf("%s must be at least %d", def.Name, *v.Min))
|
||||
}
|
||||
if v.Max != nil && num > *v.Max {
|
||||
return validationError(fmt.Sprintf("%s must be at most %d", def.Name, *v.Max))
|
||||
}
|
||||
}
|
||||
|
||||
// Pattern validation
|
||||
if v.Pattern != nil && *v.Pattern != "" && value != "" {
|
||||
re, err := regexp.Compile(*v.Pattern)
|
||||
if err == nil && !re.MatchString(value) {
|
||||
msg := def.Name + " format is invalid"
|
||||
if v.Message != nil && *v.Message != "" {
|
||||
msg = *v.Message
|
||||
}
|
||||
return validationError(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Select validation
|
||||
if def.Type == AttributeTypeSelect && value != "" {
|
||||
found := false
|
||||
for _, opt := range def.Options {
|
||||
if opt.Value == value {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return validationError(fmt.Sprintf("%s: invalid option", def.Name))
|
||||
}
|
||||
}
|
||||
|
||||
// Multi-select validation (stored as JSON array)
|
||||
if def.Type == AttributeTypeMultiSelect && value != "" {
|
||||
var values []string
|
||||
if err := json.Unmarshal([]byte(value), &values); err != nil {
|
||||
// Try comma-separated fallback
|
||||
values = strings.Split(value, ",")
|
||||
}
|
||||
for _, val := range values {
|
||||
val = strings.TrimSpace(val)
|
||||
found := false
|
||||
for _, opt := range def.Options {
|
||||
if opt.Value == val {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return validationError(fmt.Sprintf("%s: invalid option %s", def.Name, val))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validationError creates a validation error with a custom message
|
||||
func validationError(msg string) error {
|
||||
return infraerrors.BadRequest("ATTRIBUTE_VALIDATION_FAILED", msg)
|
||||
}
|
||||
|
||||
func isValidAttributeType(t UserAttributeType) bool {
|
||||
switch t {
|
||||
case AttributeTypeText, AttributeTypeTextarea, AttributeTypeNumber,
|
||||
AttributeTypeEmail, AttributeTypeURL, AttributeTypeDate,
|
||||
AttributeTypeSelect, AttributeTypeMultiSelect:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -14,6 +14,14 @@ var (
|
||||
ErrInsufficientPerms = infraerrors.Forbidden("INSUFFICIENT_PERMISSIONS", "insufficient permissions")
|
||||
)
|
||||
|
||||
// UserListFilters contains all filter options for listing users
|
||||
type UserListFilters struct {
|
||||
Status string // User status filter
|
||||
Role string // User role filter
|
||||
Search string // Search in email, username
|
||||
Attributes map[int64]string // Custom attribute filters: attributeID -> value
|
||||
}
|
||||
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, user *User) error
|
||||
GetByID(ctx context.Context, id int64) (*User, error)
|
||||
@@ -23,7 +31,7 @@ type UserRepository interface {
|
||||
Delete(ctx context.Context, id int64) error
|
||||
|
||||
List(ctx context.Context, params pagination.PaginationParams) ([]User, *pagination.PaginationResult, error)
|
||||
ListWithFilters(ctx context.Context, params pagination.PaginationParams, status, role, search string) ([]User, *pagination.PaginationResult, error)
|
||||
ListWithFilters(ctx context.Context, params pagination.PaginationParams, filters UserListFilters) ([]User, *pagination.PaginationResult, error)
|
||||
|
||||
UpdateBalance(ctx context.Context, id int64, amount float64) error
|
||||
DeductBalance(ctx context.Context, id int64, amount float64) error
|
||||
@@ -36,7 +44,6 @@ type UserRepository interface {
|
||||
type UpdateProfileRequest struct {
|
||||
Email *string `json:"email"`
|
||||
Username *string `json:"username"`
|
||||
Wechat *string `json:"wechat"`
|
||||
Concurrency *int `json:"concurrency"`
|
||||
}
|
||||
|
||||
@@ -100,10 +107,6 @@ func (s *UserService) UpdateProfile(ctx context.Context, userID int64, req Updat
|
||||
user.Username = *req.Username
|
||||
}
|
||||
|
||||
if req.Wechat != nil {
|
||||
user.Wechat = *req.Wechat
|
||||
}
|
||||
|
||||
if req.Concurrency != nil {
|
||||
user.Concurrency = *req.Concurrency
|
||||
}
|
||||
|
||||
@@ -125,4 +125,5 @@ var ProviderSet = wire.NewSet(
|
||||
ProvideTimingWheelService,
|
||||
ProvideDeferredService,
|
||||
ProvideAntigravityQuotaRefresher,
|
||||
NewUserAttributeService,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user