changed arhitecture

This commit is contained in:
2026-07-15 18:08:19 +05:00
parent 7e3a5cebcc
commit 585ba63bc2
95 changed files with 4985 additions and 1360 deletions

View File

@@ -0,0 +1,140 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/identity/userbranch"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.Repository {
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)
RETURNING id, branch_id, user_id, created_at, updated_at
)
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`
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
return scanUserBranch(row)
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM branch_user WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) {
var item userbranch.UserBranchDTO
var branchNameJSON []byte
err := row.Scan(
&item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return userbranch.UserBranchDTO{}, err
}
if err != nil {
return userbranch.UserBranchDTO{}, err
}
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
return userbranch.UserBranchDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,34 @@
package userbranch
import "time"
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type UserBranchDTO struct {
Id int64 `json:"id"`
UserId int64 `json:"userId"`
UserName string `json:"userName"`
BranchId int64 `json:"branchId"`
BranchName LocalizedText `json:"branchName"`
CreatedAt time.Time `json:"createdAt"`
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"`
}

View File

@@ -0,0 +1,152 @@
package userbranch
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/branch-users"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
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
// @Tags branch-users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateUserBranchDTO true "Branch-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users [post]
func (h *handler) create(c *gin.Context) {
var dto CreateUserBranchDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create branch user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Remove user from branch
// @Description Deletes a branch-user assignment
// @Tags branch-users
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete branch user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
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
}
}

View File

@@ -0,0 +1,9 @@
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
}