Put the user's role and branch on GET /profile, upsert role_user and branch_user on POST, and drop their list endpoints.

Also accept flexible card-order form values, move mock seed under db/mock, and regenerate Swagger.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
guwandykandCursor committed 2026-08-22 17:56:07 +05:00
1 parent 7225dc0399
commit 8795ae2195
47 files changed
+1308 -1785

No files matched your search

+20 -75
View File
@@ -4,8 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/identity/userbranch"
"online-back/pkg/client/postgresql"
@@ -23,83 +21,30 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.
return &repository{client: client, logger: logger}
}
const userBranchFromClause = ` FROM branch_user bu
JOIN branches b ON b.id = bu.branch_id
JOIN users u ON u.id = bu.user_id`
const userBranchSelectColumns = `bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at`
func (r *repository) List(ctx context.Context, filter userbranch.ListFilter) (userbranch.ListUserBranchDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+userBranchFromClause+whereClause, args...).Scan(&count); err != nil {
return userbranch.ListUserBranchDTO{}, err
}
query := `SELECT ` + userBranchSelectColumns + userBranchFromClause + whereClause + ` ORDER BY bu.id DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return userbranch.ListUserBranchDTO{}, err
}
defer rows.Close()
var items []userbranch.UserBranchDTO
for rows.Next() {
item, err := scanUserBranch(rows)
if err != nil {
return userbranch.ListUserBranchDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return userbranch.ListUserBranchDTO{}, err
}
return userbranch.ListUserBranchDTO{Count: count, Items: items}, nil
}
func buildListQuery(filter userbranch.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("bu.user_id = $%d", len(args)))
}
if filter.BranchName != "" {
args = append(args, likePattern(filter.BranchName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d
)`, n))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) {
query := `
WITH inserted AS (
INSERT INTO branch_user (branch_id, user_id)
VALUES ($1, $2)
WITH existing AS (
SELECT id FROM branch_user WHERE user_id = $2 ORDER BY id LIMIT 1
), updated AS (
UPDATE branch_user SET
branch_id = $1,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = (SELECT id FROM existing)
RETURNING id, branch_id, user_id, created_at, updated_at
), inserted AS (
INSERT INTO branch_user (branch_id, user_id)
SELECT $1, $2
WHERE NOT EXISTS (SELECT 1 FROM existing)
RETURNING id, branch_id, user_id, created_at, updated_at
), upserted AS (
SELECT * FROM updated
UNION ALL
SELECT * FROM inserted
)
SELECT inserted.id, inserted.branch_id, b.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
FROM inserted
JOIN branches b ON b.id = inserted.branch_id
JOIN users u ON u.id = inserted.user_id`
SELECT upserted.id, upserted.branch_id, b.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at
FROM upserted
JOIN branches b ON b.id = upserted.branch_id
JOIN users u ON u.id = upserted.user_id`
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
return scanUserBranch(row)
-10
View File
@@ -18,16 +18,6 @@ type UserBranchDTO struct {
UpdatedAt time.Time `json:"updatedAt"`
}
type ListUserBranchDTO struct {
Count int64 `json:"count"`
Items []UserBranchDTO `json:"items"`
}
type ListFilter struct {
UserId *int64
BranchName string
}
type CreateUserBranchDTO struct {
BranchId int64 `json:"branchId" binding:"required"`
UserId int64 `json:"userId" binding:"required"`
+1 -54
View File
@@ -4,7 +4,6 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
@@ -27,47 +26,13 @@ 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.POST("", h.create)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List branch users
// @Description Returns the authenticated user's branch-user assignments with the related user and branch
// @Tags branch-users
// @Produce json
// @Security BearerAuth
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
// @Success 200 {object} appresult.AppSuccess
// @Failure 401 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users [get]
func (h *handler) list(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
filter := ListFilter{
UserId: &userID,
BranchName: strings.TrimSpace(c.Query("branch_name")),
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list branch users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// create godoc
// @Summary Assign user to branch
// @Description Creates a branch-user assignment
// @Description Creates a branch-user assignment, or updates the user's existing branch if one is already assigned
// @Tags branch-users
// @Accept json
// @Produce json
@@ -132,21 +97,3 @@ func parseID(raw string) (int64, bool) {
}
return id, true
}
func currentUserID(c *gin.Context) (int64, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
return parseID(id)
default:
return 0, false
}
}
-1
View File
@@ -3,7 +3,6 @@ package userbranch
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListUserBranchDTO, error)
Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error)
Delete(ctx context.Context, id int64) error
}