Include assigned branches on GET user by ID.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-18 14:12:47 +05:00
parent 6191b7536c
commit 9c07439089
2 changed files with 24 additions and 22 deletions

View File

@@ -28,6 +28,21 @@ 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, role, active, created_at, updated_at`
const userBranchesJSON = `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)`
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
@@ -47,22 +62,9 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use
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)
`SELECT %s, %s
%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
userColumns, userBranchesJSON, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
@@ -186,8 +188,8 @@ func (r *repository) GetByRole(ctx context.Context, role string, filter user.Lis
}
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
item, err := scanUser(r.client.QueryRow(ctx, query, id))
query := fmt.Sprintf(`SELECT %s, %s FROM users u WHERE u.id = $1`, userColumns, userBranchesJSON)
item, err := scanStaffUser(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err
}

View File

@@ -22,10 +22,10 @@ import (
)
const (
baseURL = "/users"
fileUploadURL = "/file"
fileURL = "/file/:id"
publicFileURL = "/file/:file_name"
baseURL = "/users"
fileUploadURL = "/file"
fileURL = "/file/:id"
publicFileURL = "/file/:file_name"
)
type handler struct {
@@ -153,7 +153,7 @@ func (h *handler) listStaff(c *gin.Context) {
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user
// @Description Returns a single user with assigned branches
// @Tags user
// @Produce json
// @Security BearerAuth