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:
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
133
internal/identity/user/db/postgresql_list_test.go
Normal file
133
internal/identity/user/db/postgresql_list_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user