Return role IDs on users and related names on loan APIs.

Loan orders, paid-off letters, and repayments now include user, branch, type, and document names alongside foreign-key IDs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-19 11:58:15 +05:00
parent 2853bed2ec
commit d7cdd53597
10 changed files with 659 additions and 268 deletions

View File

@@ -2,6 +2,7 @@ package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
@@ -24,10 +25,20 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) user.Reposi
return &repository{client: client, logger: logger}
}
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.role, u.active, u.created_at, u.updated_at`
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.active, u.created_at, u.updated_at, r.id, r.code`
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at`
const userFromClause = ` FROM users u
LEFT JOIN LATERAL (
SELECT ru.role_id
FROM role_user ru
WHERE ru.user_id = u.id
ORDER BY ru.id
LIMIT 1
) ru ON true
LEFT JOIN roles r ON r.id = ru.role_id `
const userBranchesJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', b.id,
@@ -49,11 +60,10 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis
}
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
countQuery := `SELECT COUNT(*)` + userFromClause + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
@@ -62,9 +72,8 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s, %s
%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
userColumns, userBranchesJSON, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
`SELECT %s, %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
userColumns, userBranchesJSON, userFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
@@ -116,7 +125,7 @@ func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter,
var items []user.UserDTO
for rows.Next() {
item, err := scanUser(rows)
item, err := scanUserWithRoleID(rows)
if err != nil {
return user.ListUserDTO{}, err
}
@@ -132,21 +141,21 @@ func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter,
var listVisibleRoles = []string{"user"}
func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM users u `
fromClause = userFromClause
var conditions []string
conditions, args = appendNameSearch(conditions, args, filter.Search)
if len(roles) == 1 {
args = append(args, roles[0])
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
conditions = append(conditions, fmt.Sprintf(`r.code = $%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, ", ")))
conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", ")))
}
if len(conditions) == 0 {
@@ -188,7 +197,7 @@ 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, %s FROM users u WHERE u.id = $1`, userColumns, userBranchesJSON)
query := fmt.Sprintf(`SELECT %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userFromClause)
item, err := scanStaffUser(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err
@@ -233,6 +242,7 @@ func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.U
if err := assignRoleByCode(ctx, tx, item.Id, role); err != nil {
return user.UserDTO{}, err
}
item.RoleId = roleIDByCode(ctx, tx, role)
if err := tx.Commit(ctx); err != nil {
return user.UserDTO{}, err
@@ -273,6 +283,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDT
if err := replaceRoleByCode(ctx, tx, item.Id, role); err != nil {
return user.UserDTO{}, err
}
item.RoleId = roleIDByCode(ctx, tx, role)
if err := tx.Commit(ctx); err != nil {
return user.UserDTO{}, err
@@ -311,6 +322,14 @@ func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode st
return assignRoleByCode(ctx, tx, userID, roleCode)
}
func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 {
var id int64
if err := tx.QueryRow(ctx, `SELECT id FROM roles WHERE code = $1`, roleCode).Scan(&id); err != nil {
return nil
}
return &id
}
type scannable interface {
Scan(dest ...interface{}) error
}
@@ -326,15 +345,32 @@ func scanUser(row scannable) (user.UserDTO, error) {
return item, nil
}
func scanStaffUser(row scannable) (user.UserDTO, error) {
func scanUserWithRoleID(row scannable) (user.UserDTO, error) {
var item user.UserDTO
var branchesJSON []byte
var roleID sql.NullInt64
var roleCode sql.NullString
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON,
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode,
); err != nil {
return user.UserDTO{}, err
}
applyJoinedRole(&item, roleID, roleCode)
return item, nil
}
func scanStaffUser(row scannable) (user.UserDTO, error) {
var item user.UserDTO
var roleID sql.NullInt64
var roleCode sql.NullString
var branchesJSON []byte
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON,
); err != nil {
return user.UserDTO{}, err
}
applyJoinedRole(&item, roleID, roleCode)
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
item.Branches = []user.StaffBranchDTO{}
return item, nil
@@ -344,3 +380,13 @@ func scanStaffUser(row scannable) (user.UserDTO, error) {
}
return item, nil
}
func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) {
if roleCode.Valid {
item.Role = roleCode.String
}
if roleID.Valid {
id := roleID.Int64
item.RoleId = &id
}
}

View File

@@ -0,0 +1,133 @@
package db
import (
"context"
"encoding/json"
"testing"
"time"
"online-back/internal/config"
"online-back/internal/identity/user"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
func testRepo(t *testing.T) (user.Repository, func()) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
t.Cleanup(cancel)
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
Host: "localhost",
Port: "5424",
Database: "bank_db",
Username: "bank_admin",
Password: "bank@#23#@_password",
PgPoolMaxConn: 4,
})
if err != nil {
t.Skipf("postgres unavailable: %v", err)
}
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
}
func assignedRole(t *testing.T, ctx context.Context, repo user.Repository, userID int64) (id int64, code string) {
t.Helper()
poolRepo, ok := repo.(*repository)
if !ok {
t.Fatal("unexpected repository type")
}
err := poolRepo.client.QueryRow(ctx, `
SELECT r.id, r.code
FROM role_user ru
JOIN roles r ON r.id = ru.role_id
WHERE ru.user_id = $1
ORDER BY ru.id
LIMIT 1`, userID).Scan(&id, &code)
if err != nil {
t.Fatalf("lookup role_user for user %d: %v", userID, err)
}
return id, code
}
func assertJoinedRole(t *testing.T, ctx context.Context, repo user.Repository, item user.UserDTO) {
t.Helper()
wantID, wantCode := assignedRole(t, ctx, repo, item.Id)
if item.Role != wantCode {
t.Errorf("user %d role=%q, want roles.code %q", item.Id, item.Role, wantCode)
}
if item.RoleId == nil {
t.Fatalf("user %d missing roleId", item.Id)
}
if *item.RoleId != wantID {
t.Errorf("user %d roleId=%d, want roles.id %d", item.Id, *item.RoleId, wantID)
}
}
func TestListUsersRoleComesFromJoin(t *testing.T) {
repo, closeRepo := testRepo(t)
defer closeRepo()
ctx := context.Background()
filter := user.ListFilter{Page: 1, Limit: 100}
list, err := repo.List(ctx, filter)
if err != nil {
t.Fatalf("List: %v", err)
}
if list.Count == 0 || len(list.Users) == 0 {
t.Fatal("List returned no users")
}
for _, item := range list.Users {
if item.Role != "user" {
t.Errorf("List user %d role=%q, want user", item.Id, item.Role)
}
assertJoinedRole(t, ctx, repo, item)
}
clients, err := repo.GetByRole(ctx, "user", filter)
if err != nil {
t.Fatalf("GetByRole: %v", err)
}
if clients.Count == 0 {
t.Fatal("clients list empty")
}
for _, item := range clients.Users {
assertJoinedRole(t, ctx, repo, item)
}
staff, err := repo.ListStaff(ctx, filter)
if err != nil {
t.Fatalf("ListStaff: %v", err)
}
if staff.Count == 0 {
t.Fatal("staff list empty")
}
for _, item := range staff.Users {
assertJoinedRole(t, ctx, repo, item)
if item.Branches == nil {
t.Errorf("staff user %d missing branches", item.Id)
}
}
got, err := repo.GetByID(ctx, staff.Users[0].Id)
if err != nil {
t.Fatalf("GetByID: %v", err)
}
assertJoinedRole(t, ctx, repo, got)
raw, err := json.Marshal(list.Users[0])
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(raw, &payload); err != nil {
t.Fatal(err)
}
if _, ok := payload["role"]; !ok {
t.Errorf("json missing role: %s", raw)
}
if _, ok := payload["roleId"]; !ok {
t.Errorf("json missing roleId: %s", raw)
}
}

View File

@@ -24,6 +24,7 @@ type UserDTO struct {
Phone string `json:"phone"`
Avatar string `json:"avatar"`
Role string `json:"role"`
RoleId *int64 `json:"roleId,omitempty"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`

View File

@@ -60,7 +60,7 @@ func (h *handler) RegisterPublic(engine *gin.Engine) {
// list godoc
// @Summary List users
// @Description Returns paginated users with role user, with optional filters
// @Description Returns paginated users with role user, including roleId
// @Tags user
// @Produce json
// @Security BearerAuth
@@ -91,7 +91,7 @@ func (h *handler) list(c *gin.Context) {
// listClients godoc
// @Summary List client users
// @Description Returns paginated client users (role user, not assigned to any branch)
// @Description Returns paginated client users (role user, not assigned to any branch), including roleId
// @Tags user
// @Produce json
// @Security BearerAuth
@@ -122,7 +122,7 @@ func (h *handler) listClients(c *gin.Context) {
// listStaff godoc
// @Summary List staff users
// @Description Returns paginated users assigned to branches (from branch_user), including each user's branches.
// @Description Returns paginated users assigned to branches (from branch_user), including each user's branches and roleId.
// @Tags user
// @Produce json
// @Security BearerAuth
@@ -153,7 +153,7 @@ func (h *handler) listStaff(c *gin.Context) {
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user with assigned branches
// @Description Returns a single user with assigned branches and roleId
// @Tags user
// @Produce json
// @Security BearerAuth