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

+75 -13
View File
@@ -12,16 +12,14 @@ import (
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
logger *logging.Logger
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) activitylog.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "activity_logs", activityLogColumnsSQL, scanActivityLog),
logger: logger,
client: client,
logger: logger,
}
}
@@ -31,13 +29,52 @@ var activityLogColumns = []string{
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
const activityLogFromClause = ` FROM activity_logs al
LEFT JOIN users u ON u.id = al.user_id
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 activityLogSelectColumns = `al.id, al.user_id, al.method, al.path, al.module, al.action, al.status_code, al.request_body, al.ip, al.created_at, COALESCE(u.username, ''), COALESCE(r.code, '')`
func (r *repository) List(ctx context.Context, filter activitylog.ListFilter) (activitylog.ListActivityLogDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM activity_logs al`+whereClause, args...).Scan(&count); err != nil {
return activitylog.ListActivityLogDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY al.id DESC LIMIT $%d OFFSET $%d`,
activityLogSelectColumns, activityLogFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return activitylog.ListActivityLogDTO{}, err
}
defer rows.Close()
var items []activitylog.ActivityLogDTO
for rows.Next() {
item, err := scanActivityLog(rows)
if err != nil {
return activitylog.ListActivityLogDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return activitylog.ListActivityLogDTO{}, err
}
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
}
@@ -47,17 +84,17 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.user_id = $%d", len(args)))
}
if filter.Module != "" {
args = append(args, filter.Module)
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.module = $%d", len(args)))
}
if filter.Action != "" {
args = append(args, filter.Action)
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.action = $%d", len(args)))
}
if len(conditions) == 0 {
@@ -68,12 +105,28 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
}
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + activityLogSelectColumns + activityLogFromClause + ` WHERE al.id = $1`
return scanActivityLog(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityLogDTO) (activitylog.ActivityLogDTO, error) {
query := `INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ` + activityLogColumnsSQL
query := `
WITH inserted AS (
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
RETURNING ` + activityLogColumnsSQL + `
)
SELECT ` + activityLogSelectColumns + `
FROM inserted al
LEFT JOIN users u ON u.id = al.user_id
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`
row := r.client.QueryRow(ctx, query,
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
@@ -84,14 +137,23 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
var item activitylog.ActivityLogDTO
var requestBody []byte
var username, role string
err := row.Scan(
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
&username, &role,
)
if err != nil {
return activitylog.ActivityLogDTO{}, err
}
item.RequestBody = requestBody
if item.UserId != nil {
item.User = &activitylog.UserInfo{
Id: *item.UserId,
Username: username,
Role: role,
}
}
return item, nil
}
+7
View File
@@ -5,9 +5,16 @@ import (
"time"
)
type UserInfo struct {
Id int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
}
type ActivityLogDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"userId"`
User *UserInfo `json:"user"`
Method string `json:"method"`
Path string `json:"path"`
Module string `json:"module"`
+42 -13
View File
@@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
@@ -34,7 +35,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// list godoc
// @Summary List activity logs
// @Description Returns a paginated audit trail of user actions (create/update/delete)
// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.
// @Tags activity-logs
// @Produce json
// @Security BearerAuth
@@ -79,7 +80,13 @@ func (h *handler) list(c *gin.Context) {
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
// GET /activity-logs/card-orders → list that module instead of 400.
q := c.Request.URL.Query()
if q.Get("module") == "" {
q.Set("module", c.Param("id"))
c.Request.URL.RawQuery = q.Encode()
}
h.list(c)
return
}
@@ -117,18 +124,16 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
Limit: defaultLimit,
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
filter.Module = c.Query("module")
filter.Action = c.Query("action")
filter.Module = queryValue(c, "module")
filter.Action = queryValue(c, "action")
if raw := c.Query("page"); raw != "" {
if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
@@ -136,13 +141,37 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > maxLimit {
limit = maxLimit
}
filter.Limit = limit
}
return filter, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
raw := queryValue(c, keys...)
if raw == "" {
return nil, true
}
id, ok := parseID(raw)
if !ok {
return nil, false
}
return &id, true
}
@@ -0,0 +1,96 @@
package activitylog
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"testing"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
type stubRepository struct {
mu sync.Mutex
listFilter ListFilter
listResult ListActivityLogDTO
created []CreateActivityLogDTO
}
func (s *stubRepository) List(_ context.Context, filter ListFilter) (ListActivityLogDTO, error) {
s.listFilter = filter
return s.listResult, nil
}
func (s *stubRepository) GetByID(_ context.Context, _ int64) (ActivityLogDTO, error) {
return ActivityLogDTO{}, nil
}
func (s *stubRepository) Create(_ context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.created = append(s.created, dto)
return ActivityLogDTO{Id: 1}, nil
}
func (s *stubRepository) createdEntries() []CreateActivityLogDTO {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]CreateActivityLogDTO, len(s.created))
copy(out, s.created)
return out
}
func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req := httptest.NewRequest(http.MethodGet, "/activity-logs?user_id=undefined&module=card-orders&limit=1000&page=2", nil)
c.Request = req
filter, ok := parseListFilter(c)
if !ok {
t.Fatal("expected filter to parse")
}
if filter.UserId != nil {
t.Fatalf("user_id should be ignored, got %v", *filter.UserId)
}
if filter.Module != "card-orders" {
t.Fatalf("module=%q", filter.Module)
}
if filter.Limit != maxLimit {
t.Fatalf("limit=%d", filter.Limit)
}
if filter.Page != 2 {
t.Fatalf("page=%d", filter.Page)
}
}
func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &stubRepository{listResult: ListActivityLogDTO{Count: 0, Logs: []ActivityLogDTO{}}}
h := &handler{logger: logging.GetLogger(), repository: repo}
r := gin.New()
group := r.Group("/activity-logs")
group.GET("", h.list)
group.GET("/:id", h.getByID)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/activity-logs/card-orders?limit=1000", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if repo.listFilter.Module != "card-orders" {
t.Fatalf("module=%q", repo.listFilter.Module)
}
if repo.listFilter.Limit != maxLimit {
t.Fatalf("limit=%d", repo.listFilter.Limit)
}
}
+73 -35
View File
@@ -15,53 +15,87 @@ import (
"github.com/gin-gonic/gin"
)
// sensitiveFieldSubstrings marks request body keys that must never be
// persisted verbatim (login passwords, branch billing credentials, etc).
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
const writeTimeout = 5 * time.Second
const (
writeTimeout = 5 * time.Second
queueSize = 1024
workers = 2
)
type recorder struct {
repository Repository
logger *logging.Logger
queue chan CreateActivityLogDTO
}
// Record returns a global gin middleware that persists every mutating
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
// activity_logs - e.g. creating a card or attaching a user to a branch.
// Read-only (GET) requests are not recorded. It must run after
// appresult.JwtTokenCheck has set "id" in the context, which happens
// naturally here since c.Next() runs the rest of the chain first.
// Read-only (GET) requests are not recorded. After the handler finishes
// the entry is queued (the client is not blocked) and a small worker
// pool writes it. JwtTokenCheck sets "id" during c.Next(), which is why
// the user is read afterwards.
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
return newRecorder(repository, logger).handle
}
body := readAndRestoreBody(c)
func newRecorder(repository Repository, logger *logging.Logger) *recorder {
r := &recorder{
repository: repository,
logger: logger,
queue: make(chan CreateActivityLogDTO, queueSize),
}
for i := 0; i < workers; i++ {
go r.worker()
}
return r
}
func (r *recorder) handle(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
userID := currentUserID(c)
if userID == nil {
return
body := readAndRestoreBody(c)
c.Next()
userID := currentUserID(c)
if userID == nil {
return
}
id := *userID
module, action := describeRoute(c)
r.enqueue(CreateActivityLogDTO{
UserId: &id,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
})
}
func (r *recorder) enqueue(entry CreateActivityLogDTO) {
select {
case r.queue <- entry:
default:
r.logger.Errorf("activity log queue full, dropping %s %s", entry.Method, entry.Path)
}
}
func (r *recorder) worker() {
for entry := range r.queue {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
if _, err := r.repository.Create(ctx, entry); err != nil {
r.logger.Errorf("record activity log failed: %v", err)
}
module, action := describeRoute(c)
entry := CreateActivityLogDTO{
UserId: userID,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
defer cancel()
if _, err := repository.Create(ctx, entry); err != nil {
logger.Errorf("record activity log failed: %v", err)
}
}()
cancel()
}
}
@@ -80,9 +114,13 @@ func readAndRestoreBody(c *gin.Context) []byte {
}
data, err := io.ReadAll(c.Request.Body)
if err != nil {
c.Request.Body = io.NopCloser(bytes.NewReader(nil))
return nil
}
// Restore Body for ShouldBindJSON and cache it so ShouldBindBodyWithJSON
// still works after this middleware has already consumed the stream.
c.Request.Body = io.NopCloser(bytes.NewReader(data))
c.Set(gin.BodyBytesKey, data)
return data
}
@@ -0,0 +1,71 @@
package activitylog
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
func TestRecordLeavesJSONBodyForHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &stubRepository{}
r := gin.New()
r.Use(Record(repo, logging.GetLogger()))
r.POST("/api/admin/card-orders", func(c *gin.Context) {
c.Set("id", "3")
var dto struct {
CustomerName string `json:"customerName" binding:"required"`
Region string `json:"region" binding:"required"`
}
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, dto)
})
body := `{"customerName":"Simple","region":"Aşgabat"}`
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-orders", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
deadline := time.Now().Add(time.Second)
var created []CreateActivityLogDTO
for time.Now().Before(deadline) {
created = repo.createdEntries()
if len(created) > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(created) == 0 {
t.Fatal("expected activity log to be recorded")
}
if created[0].Module != "card-orders" {
t.Fatalf("module=%q", created[0].Module)
}
if created[0].StatusCode != http.StatusCreated {
t.Fatalf("statusCode=%d", created[0].StatusCode)
}
var logged map[string]interface{}
if err := json.Unmarshal(created[0].RequestBody, &logged); err != nil {
t.Fatalf("request body: %v", err)
}
if logged["customerName"] != "Simple" {
t.Fatalf("logged body=%v", logged)
}
}
+76 -20
View File
@@ -2,6 +2,8 @@ package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strings"
"unicode"
@@ -38,10 +40,36 @@ const (
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
LIMIT 1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
FROM users WHERE id = $1`
)
const profileFromClause = ` 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 profileBranchesJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', b.id,
'uniqueCode', COALESCE(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)`
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
r.id, r.code, r.name, ` + profileBranchesJSON + profileFromClause + ` WHERE u.id = $1`
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone)
if phone != "" {
@@ -66,31 +94,39 @@ func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredenti
}
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
return profile, err
return scanProfile(r.client.QueryRow(ctx, profileQuery, id))
}
const updateProfileQuery = `
UPDATE users SET
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $6
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
WHERE id = $6`
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, updateProfileQuery,
tag, err := r.client.Exec(ctx, updateProfileQuery,
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
).Scan(
)
if err != nil {
return auth.UserProfileDTO{}, err
}
if tag.RowsAffected() == 0 {
return auth.UserProfileDTO{}, pgx.ErrNoRows
}
return r.GetProfile(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
var roleID sql.NullInt64
var roleCode, roleName sql.NullString
var branchesJSON []byte
err := row.Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
@@ -98,11 +134,31 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
&roleID,
&roleCode,
&roleName,
&branchesJSON,
)
if errors.Is(err, pgx.ErrNoRows) {
if err != nil {
return auth.UserProfileDTO{}, err
}
return profile, err
if roleID.Valid {
profile.Role = &auth.ProfileRoleDTO{
Id: roleID.Int64,
Code: roleCode.String,
Name: roleName.String,
}
}
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
profile.Branches = []auth.ProfileBranchDTO{}
return profile, nil
}
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
}
return profile, nil
}
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
+27 -7
View File
@@ -12,14 +12,34 @@ type RefreshTokenDTO struct {
RefreshToken string `json:"refreshToken" binding:"required"`
}
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type ProfileRoleDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
}
type ProfileBranchDTO struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name"`
}
type UserProfileDTO struct {
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"`
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"`
CreatedAt time.Time `json:"createdAt"`
}
type UpdateProfileDTO struct {
+1 -1
View File
@@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) {
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Description Returns the authenticated user's profile with role and branches
// @Tags auth
// @Produce json
// @Security BearerAuth
-48
View File
@@ -1,48 +0,0 @@
package auth
import "testing"
func TestNormalizePhone(t *testing.T) {
tests := []struct {
in, want string
}{
{"+99361531216", "+993 61 53 12 16"},
{"+993 61 92 92 48", "+993 61 92 92 48"},
{"+99361929248", "+993 61 92 92 48"},
{"99361929248", "+993 61 92 92 48"},
{"61929248", "+993 61 92 92 48"},
{"8 61929248", "+993 61 92 92 48"},
{"61 92 92 48", "+993 61 92 92 48"},
}
for _, tt := range tests {
got, err := NormalizePhone(tt.in)
if err != nil {
t.Fatalf("NormalizePhone(%q) unexpected error: %v", tt.in, err)
}
if got != tt.want {
t.Errorf("NormalizePhone(%q) = %q, want %q", tt.in, got, tt.want)
}
}
if _, err := NormalizePhone("123"); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(123) error = %v, want ErrInvalidPhone", err)
}
validPrefixes := []string{"61", "62", "63", "64", "65", "71", "72"}
for _, prefix := range validPrefixes {
in := prefix + "929248"
if _, err := NormalizePhone(in); err != nil {
t.Errorf("NormalizePhone(%q) unexpected error: %v", in, err)
}
}
invalid := []string{
"60929248", "66929248", "70929248", "73929248", "81929248",
"+99366531216", "+99360929248",
}
for _, in := range invalid {
if _, err := NormalizePhone(in); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(%q) error = %v, want ErrInvalidPhone", in, err)
}
}
}
-293
View File
@@ -1,293 +0,0 @@
package auth
import (
"context"
"errors"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
type fakeRepo struct {
exists bool
usernameTaken bool
verification Verification
getErr error
userID int
userByName UserIdentity
userByNameErr error
loginUser UserCredentials
loginErr error
lastLogin LoginDTO
}
func (f *fakeRepo) Login(_ context.Context, dto LoginDTO) (UserCredentials, error) {
f.lastLogin = dto
if f.loginErr != nil {
return UserCredentials{}, f.loginErr
}
return f.loginUser, nil
}
func (f *fakeRepo) GetUserByID(context.Context, int) (UserCredentials, error) {
return UserCredentials{}, errors.New("not implemented")
}
func (f *fakeRepo) GetProfile(context.Context, int) (UserProfileDTO, error) {
return UserProfileDTO{}, errors.New("not implemented")
}
func (f *fakeRepo) UpdateProfile(context.Context, int, UpdateProfileDTO) (UserProfileDTO, error) {
return UserProfileDTO{}, errors.New("not implemented")
}
func (f *fakeRepo) UserExists(context.Context, string, string) (bool, error) {
return f.exists, nil
}
func (f *fakeRepo) UsernameTaken(context.Context, string, string) (bool, error) {
return f.usernameTaken, nil
}
func (f *fakeRepo) UpsertVerification(_ context.Context, v Verification) error {
f.verification = v
return nil
}
func (f *fakeRepo) GetVerificationByPhone(context.Context, string) (Verification, error) {
return f.verification, f.getErr
}
func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
f.verification.Attempts++
return nil
}
func (f *fakeRepo) CompleteRegistration(context.Context, Verification) (int, error) {
return f.userID, nil
}
func (f *fakeRepo) GetUserByName(context.Context, string) (UserIdentity, error) {
if f.userByNameErr != nil {
return UserIdentity{}, f.userByNameErr
}
return f.userByName, nil
}
func (f *fakeRepo) CompletePasswordReset(context.Context, int, int64, string) error {
return nil
}
type fakeSMS struct {
phone, message string
err error
}
func (f *fakeSMS) Send(_ context.Context, phone, message string) error {
f.phone = phone
f.message = message
return f.err
}
func validRegisterDTO() RegisterDTO {
return RegisterDTO{
Name: "Berdi Berdiyew",
Phone: "+993 61 92 92 48",
Username: "berdi",
Password: "secret1",
PasswordConfirm: "secret1",
}
}
func TestLoginRequiresNameOrPhone(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginIgnoresInvalidPhoneWhenNamePresent(t *testing.T) {
repo := &fakeRepo{loginErr: errors.New("stop after lookup")}
_, _ = NewService(repo, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "admin",
Phone: "string",
Password: "Test1234!",
})
if repo.lastLogin.Name != "admin" {
t.Fatalf("name = %q, want admin", repo.lastLogin.Name)
}
if repo.lastLogin.Phone != "" {
t.Fatalf("phone = %q, want empty", repo.lastLogin.Phone)
}
}
func TestLoginInvalidPhoneWithoutName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Phone: "string",
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginWrongPassword(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("secret1"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
_, err = NewService(&fakeRepo{loginUser: UserCredentials{Id: 7, Password: string(hash)}}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "Berdi Berdiyew",
Password: "wrong",
})
if !errors.Is(err, ErrInvalidCredentials) {
t.Fatalf("error = %v, want ErrInvalidCredentials", err)
}
}
func TestRegisterPasswordMismatch(t *testing.T) {
dto := validRegisterDTO()
dto.PasswordConfirm = "other"
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Register(context.Background(), dto)
if !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
}
}
func TestRegisterConflict(t *testing.T) {
_, err := NewService(&fakeRepo{exists: true}, &fakeSMS{}).Register(context.Background(), validRegisterDTO())
if !errors.Is(err, ErrConflict) {
t.Fatalf("error = %v, want ErrConflict", err)
}
}
func TestRegisterSendsSMS(t *testing.T) {
repo := &fakeRepo{}
sender := &fakeSMS{}
result, err := NewService(repo, sender).Register(context.Background(), validRegisterDTO())
if err != nil {
t.Fatalf("Register: %v", err)
}
if result.Phone != "+993 61 92 92 48" {
t.Errorf("phone = %q", result.Phone)
}
if result.ExpiresIn != 60 {
t.Errorf("expiresIn = %d", result.ExpiresIn)
}
if sender.phone != result.Phone {
t.Errorf("sms phone = %q", sender.phone)
}
if !strings.Contains(sender.message, "123456") {
t.Errorf("sms message = %q", sender.message)
}
if repo.verification.Password == "secret1" {
t.Fatal("password stored in plaintext")
}
}
func TestVerifyWrongCode(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
repo := &fakeRepo{verification: Verification{
ID: 1,
Phone: "+993 61 92 92 48",
CodeHash: string(hash),
ExpiresAt: time.Now().UTC().Add(time.Minute),
}}
_, err = NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
Phone: "+993 61 92 92 48",
Code: "000000",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
if repo.verification.Attempts != 1 {
t.Errorf("attempts = %d, want 1", repo.verification.Attempts)
}
}
func TestVerifyExpiredCode(t *testing.T) {
repo := &fakeRepo{verification: Verification{
ExpiresAt: time.Now().UTC().Add(-time.Minute),
}}
_, err := NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
Phone: "+993 61 92 92 48",
Code: "123456",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}
func TestForgotPasswordRequiresName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestForgotPasswordNotFound(t *testing.T) {
_, err := NewService(&fakeRepo{userByNameErr: ErrNotFound}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound", err)
}
}
func TestForgotPasswordSendsSMS(t *testing.T) {
repo := &fakeRepo{userByName: UserIdentity{
Id: 7,
Name: "Berdi Berdiyew",
Username: "berdi",
Phone: "+993 61 92 92 48",
}}
sender := &fakeSMS{}
result, err := NewService(repo, sender).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if err != nil {
t.Fatalf("ForgotPassword: %v", err)
}
if result.Phone != "+993 61 92 92 48" {
t.Errorf("phone = %q", result.Phone)
}
if sender.phone != result.Phone {
t.Errorf("sms phone = %q", sender.phone)
}
if !strings.Contains(sender.message, "123456") {
t.Errorf("sms message = %q", sender.message)
}
}
func TestResetPasswordMismatch(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "123456",
Password: "secret1",
PasswordConfirm: "other",
})
if !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
}
}
func TestResetPasswordWrongCode(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
repo := &fakeRepo{
userByName: UserIdentity{Id: 7, Phone: "+993 61 92 92 48"},
verification: Verification{
ID: 1,
Phone: "+993 61 92 92 48",
CodeHash: string(hash),
ExpiresAt: time.Now().UTC().Add(time.Minute),
},
}
_, err = NewService(repo, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "000000",
Password: "secret1",
PasswordConfirm: "secret1",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}
+20 -72
View File
@@ -3,8 +3,6 @@ package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/roleusers"
"online-back/pkg/client/postgresql"
@@ -22,80 +20,30 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.R
return &repository{client: client, logger: logger}
}
const roleUserFromClause = ` FROM role_user ru
JOIN roles r ON r.id = ru.role_id
JOIN users u ON u.id = ru.user_id`
const roleUserSelectColumns = `ru.id, ru.role_id, r.name, ru.user_id, u.name, ru.created_at, ru.updated_at`
func (r *repository) List(ctx context.Context, filter roleusers.ListFilter) (roleusers.ListRoleUserDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+roleUserFromClause+whereClause, args...).Scan(&count); err != nil {
return roleusers.ListRoleUserDTO{}, err
}
query := `SELECT ` + roleUserSelectColumns + roleUserFromClause + whereClause + ` ORDER BY ru.id DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return roleusers.ListRoleUserDTO{}, err
}
defer rows.Close()
var items []roleusers.RoleUserDTO
for rows.Next() {
item, err := scanRoleUser(rows)
if err != nil {
return roleusers.ListRoleUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return roleusers.ListRoleUserDTO{}, err
}
return roleusers.ListRoleUserDTO{Count: count, Items: items}, nil
}
func buildListQuery(filter roleusers.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("ru.user_id = $%d", len(args)))
}
if filter.RoleName != "" {
args = append(args, likePattern(filter.RoleName))
conditions = append(conditions, fmt.Sprintf("r.name ILIKE $%d", len(args)))
}
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 roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) {
query := `
WITH inserted AS (
INSERT INTO role_user (role_id, user_id)
VALUES ($1, $2)
WITH existing AS (
SELECT id FROM role_user WHERE user_id = $2 ORDER BY id LIMIT 1
), updated AS (
UPDATE role_user SET
role_id = $1,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = (SELECT id FROM existing)
RETURNING id, role_id, user_id, created_at, updated_at
), inserted AS (
INSERT INTO role_user (role_id, user_id)
SELECT $1, $2
WHERE NOT EXISTS (SELECT 1 FROM existing)
RETURNING id, role_id, user_id, created_at, updated_at
), upserted AS (
SELECT * FROM updated
UNION ALL
SELECT * FROM inserted
)
SELECT inserted.id, inserted.role_id, r.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
FROM inserted
JOIN roles r ON r.id = inserted.role_id
JOIN users u ON u.id = inserted.user_id`
SELECT upserted.id, upserted.role_id, r.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at
FROM upserted
JOIN roles r ON r.id = upserted.role_id
JOIN users u ON u.id = upserted.user_id`
row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId)
return scanRoleUser(row)
-10
View File
@@ -12,16 +12,6 @@ type RoleUserDTO struct {
UpdatedAt time.Time `json:"updatedAt"`
}
type ListRoleUserDTO struct {
Count int64 `json:"count"`
Items []RoleUserDTO `json:"items"`
}
type ListFilter struct {
UserId *int64
RoleName string
}
type CreateRoleUserDTO struct {
RoleId int64 `json:"roleId" 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 role users
// @Description Returns the authenticated user's role-user assignments with the related user and role
// @Tags role-users
// @Produce json
// @Security BearerAuth
// @Param role_name query string false "Filter by role name"
// @Success 200 {object} appresult.AppSuccess
// @Failure 401 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /role-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,
RoleName: strings.TrimSpace(c.Query("role_name")),
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list role users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// create godoc
// @Summary Assign user to role
// @Description Creates a role-user assignment
// @Description Creates a role-user assignment, or updates the user's existing role if one is already assigned
// @Tags role-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 roleusers
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListRoleUserDTO, error)
Create(ctx context.Context, dto CreateRoleUserDTO) (RoleUserDTO, error)
Delete(ctx context.Context, id int64) error
}
+1 -4
View File
@@ -28,8 +28,7 @@ import (
"github.com/gin-gonic/gin"
)
// Register wires every identity module's handler onto router.
// engine is the root gin engine so public file GET can live at /file/:file_name.
func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Client, logger *logging.Logger) {
userH := user.NewHandler(logger, userdb.NewRepository(client, logger))
userH.Register(router)
@@ -43,8 +42,6 @@ func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Cli
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)),
// Swap sms.NewLogSender for your SMS provider: it only needs to
// implement sms.Sender (Send(ctx, phone, message)).
auth.NewHandler(logger, authdb.NewRepository(client, logger), sms.NewLogSender(logger)),
role.NewHandler(logger, roledb.NewRepository(client, logger)),
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
@@ -1,133 +0,0 @@
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)
}
}
+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
}