Add forgot-password SMS reset, client/staff user lists, and regenerate Swagger.
Fold follow-up migrations into init, expose GET /users/clients and /users/staff, and refresh seed data. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -29,8 +29,73 @@ const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.usernam
|
||||
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
|
||||
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
||||
}
|
||||
|
||||
func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause := ` FROM users u `
|
||||
whereClause, args := buildStaffWhere(filter)
|
||||
|
||||
var count int64
|
||||
countQuery := `SELECT COUNT(*)` + fromClause + whereClause
|
||||
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s, COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
'id', b.id,
|
||||
'uniqueCode', b.unique_code,
|
||||
'name', b.name
|
||||
) ORDER BY b.id)
|
||||
FROM (
|
||||
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = u.id
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::json)
|
||||
%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
|
||||
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []user.UserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanStaffUser(rows)
|
||||
if err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
|
||||
return user.ListUserDTO{Count: count, Users: items}, nil
|
||||
}
|
||||
|
||||
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
|
||||
conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`}
|
||||
if filter.Username != "" {
|
||||
args = append(args, likePattern(filter.Username))
|
||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, len(args)))
|
||||
}
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter, fromClause, whereClause string, args []interface{}) (user.ListUserDTO, error) {
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
@@ -65,11 +130,9 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis
|
||||
return user.ListUserDTO{Count: count, Users: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
return buildFilteredListQuery(filter, "")
|
||||
}
|
||||
var listVisibleRoles = []string{"user"}
|
||||
|
||||
func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) {
|
||||
func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM users u `
|
||||
|
||||
var conditions []string
|
||||
@@ -78,10 +141,17 @@ func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, wh
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
|
||||
}
|
||||
if role != "" {
|
||||
args = append(args, role)
|
||||
if len(roles) == 1 {
|
||||
args = append(args, roles[0])
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
|
||||
} else if len(roles) > 0 {
|
||||
placeholders := make([]string, len(roles))
|
||||
for i, role := range roles {
|
||||
args = append(args, role)
|
||||
placeholders[i] = fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
conditions = append(conditions, fmt.Sprintf(`u.role IN (%s)`, strings.Join(placeholders, ", ")))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
@@ -100,39 +170,7 @@ func likePattern(term string) string {
|
||||
|
||||
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `,
|
||||
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []user.UserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanUser(rows)
|
||||
if err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return user.ListUserDTO{}, err
|
||||
}
|
||||
|
||||
return user.ListUserDTO{Count: count, Users: items}, nil
|
||||
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
|
||||
@@ -222,3 +260,26 @@ func scanUser(row scannable) (user.UserDTO, error) {
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func scanStaffUser(row scannable) (user.UserDTO, error) {
|
||||
var item user.UserDTO
|
||||
var socialMedia []byte
|
||||
var branchesJSON []byte
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
||||
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON,
|
||||
); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
|
||||
item.Branches = []user.StaffBranchDTO{}
|
||||
return item, nil
|
||||
}
|
||||
if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -8,21 +8,34 @@ type SocialMedia struct {
|
||||
Telegram string `json:"telegram"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type StaffBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
}
|
||||
|
||||
type UserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Branches []StaffBranchDTO `json:"branches,omitempty"`
|
||||
}
|
||||
|
||||
type CreateUserDTO struct {
|
||||
|
||||
@@ -40,7 +40,8 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/role", h.listUsersByRole)
|
||||
group.GET("/clients", h.listClients)
|
||||
group.GET("/staff", h.listStaff)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
@@ -57,7 +58,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users with optional filters
|
||||
// @Description Returns paginated users with role user, with optional filters
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
@@ -85,41 +86,29 @@ func (h *handler) list(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// listUsersByRole godoc
|
||||
// @Summary List users by role
|
||||
// @Description Returns paginated users filtered by role
|
||||
// listClients godoc
|
||||
// @Summary List client users
|
||||
// @Description Returns paginated users from the users table with role user
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role query string true "user role"
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/role [get]
|
||||
func (h *handler) listUsersByRole(c *gin.Context) {
|
||||
role := strings.TrimSpace(c.Query("role"))
|
||||
if role == "" {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
// @Router /users/clients [get]
|
||||
func (h *handler) listClients(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByRole(c.Request.Context(), role, filter)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
item, err := h.repository.GetByRole(c.Request.Context(), "user", filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user failed: %v", err)
|
||||
h.logger.Errorf("list client users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -127,6 +116,36 @@ func (h *handler) listUsersByRole(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// listStaff godoc
|
||||
// @Summary List staff users
|
||||
// @Description Returns paginated users assigned to branches (from branch_user), including each user's branches.
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/staff [get]
|
||||
func (h *handler) listStaff(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.ListStaff(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list staff users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get user by ID
|
||||
// @Description Returns a single user
|
||||
|
||||
@@ -4,6 +4,7 @@ import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
|
||||
ListStaff(ctx context.Context, filter ListFilter) (ListUserDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (UserDTO, error)
|
||||
GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error)
|
||||
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
|
||||
|
||||
Reference in New Issue
Block a user