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)
}
}