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

@@ -7,6 +7,22 @@ CREATE TABLE IF NOT EXISTS roles (
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS role_user (
id bigserial PRIMARY KEY,
role_id bigint REFERENCES roles(id),
user_id bigint REFERENCES users(id),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS permission_user (
id bigserial PRIMARY KEY,
permission_id bigint REFERENCES permissions(id),
user_id bigint REFERENCES users(id),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
"id" bigserial primary key,
"email" character varying(250) NOT NULL DEFAULT '',
@@ -49,9 +65,9 @@ CREATE TABLE IF NOT EXISTS branches (
unique_code character varying(255) UNIQUE,
name json NOT NULL DEFAULT '{}'::json,
address json NOT NULL DEFAULT '{}'::json,
region character varying(2) NOT NULL DEFAULT '',
region character varying(20) NOT NULL DEFAULT '',
province_id bigint,
phone_numbers json NOT NULL DEFAULT '[]'::json,
phone_numbers character varying(255) NOT NULL DEFAULT '',
billing_username character varying(255) NOT NULL DEFAULT '',
billing_password character varying(255) NOT NULL DEFAULT '',
billing_swift_username character varying(255) NOT NULL DEFAULT '',
@@ -326,4 +342,5 @@ CREATE TABLE IF NOT EXISTS cards (
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT cards_user_id_fkey
FOREIGN KEY ("user_id") REFERENCES users(id)
);
);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -19,16 +19,6 @@ definitions:
status:
type: boolean
type: object
auth.CreateBranchUserDTO:
properties:
branchId:
type: integer
userId:
type: integer
required:
- branchId
- userId
type: object
auth.LoginDTO:
properties:
email:
@@ -46,6 +36,21 @@ definitions:
required:
- refreshToken
type: object
auth.UpdateProfileDTO:
properties:
avatar:
type: string
firstName:
type: string
lastName:
type: string
name:
type: string
phone:
type: string
required:
- name
type: object
branches.CreateBranchDTO:
properties:
active:
@@ -71,9 +76,7 @@ definitions:
name:
$ref: '#/definitions/branches.LocalizedText'
phoneNumbers:
items:
type: string
type: array
type: string
provinceId:
type: integer
region:
@@ -119,9 +122,7 @@ definitions:
name:
$ref: '#/definitions/branches.LocalizedText'
phoneNumbers:
items:
type: string
type: array
type: string
provinceId:
type: integer
region:
@@ -289,6 +290,112 @@ definitions:
- passportTwo
- region
type: object
cardpinorders.CreateCardPinOrderDTO:
properties:
bornAt:
type: string
branchId:
type: integer
cardNumber:
type: string
cardTypeId:
type: integer
customerName:
type: string
customerPatronicName:
type: string
customerSurname:
type: string
notes:
type: string
passportFour:
type: string
passportId:
type: string
passportOne:
type: string
passportSerie:
type: string
passportThree:
type: string
passportTwo:
type: string
phone:
type: string
region:
type: string
status:
type: string
uniqueId:
type: string
userId:
type: integer
required:
- branchId
- cardTypeId
- customerName
- customerSurname
- passportFour
- passportId
- passportOne
- passportSerie
- passportThree
- passportTwo
- region
type: object
cardpinorders.UpdateCardPinOrderDTO:
properties:
bornAt:
type: string
branchId:
type: integer
cardNumber:
type: string
cardTypeId:
type: integer
customerName:
type: string
customerPatronicName:
type: string
customerSurname:
type: string
notes:
type: string
passportFour:
type: string
passportId:
type: string
passportOne:
type: string
passportSerie:
type: string
passportThree:
type: string
passportTwo:
type: string
phone:
type: string
region:
type: string
status:
type: string
uniqueId:
type: string
userId:
type: integer
required:
- branchId
- cardTypeId
- customerName
- customerSurname
- passportFour
- passportId
- passportOne
- passportSerie
- passportThree
- passportTwo
- region
type: object
cards.CreateCardDTO:
properties:
month:
@@ -911,6 +1018,16 @@ definitions:
- guardName
- name
type: object
permissionuser.CreatePermissionUserDTO:
properties:
permissionId:
type: integer
userId:
type: integer
required:
- permissionId
- userId
type: object
province.CreateProvinceDTO:
properties:
active:
@@ -1007,6 +1124,16 @@ definitions:
- guardName
- name
type: object
roleusers.CreateRoleUserDTO:
properties:
roleId:
type: integer
userId:
type: integer
required:
- roleId
- userId
type: object
user.CreateUserDTO:
properties:
active:
@@ -1077,6 +1204,16 @@ definitions:
- name
- username
type: object
userbranch.CreateUserBranchDTO:
properties:
branchId:
type: integer
userId:
type: integer
required:
- branchId
- userId
type: object
host: localhost:5050
info:
contact: {}
@@ -1085,6 +1222,34 @@ info:
version: "1.0"
paths:
/branch-users:
get:
description: Returns the authenticated user's branch-user assignments with the
related user and branch
parameters:
- description: Filter by branch name (en, ru, tm)
in: query
name: branch_name
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List branch users
tags:
- branch-users
post:
consumes:
- application/json
@@ -1095,7 +1260,7 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/auth.CreateBranchUserDTO'
$ref: '#/definitions/userbranch.CreateUserBranchDTO'
produces:
- application/json
responses:
@@ -1115,7 +1280,7 @@ paths:
- BearerAuth: []
summary: Assign user to branch
tags:
- auth
- branch-users
/branch-users/{id}:
delete:
description: Deletes a branch-user assignment
@@ -1148,7 +1313,7 @@ paths:
- BearerAuth: []
summary: Remove user from branch
tags:
- auth
- branch-users
/branches:
get:
description: Returns paginated branches with optional filters
@@ -1529,6 +1694,196 @@ paths:
summary: Update card order
tags:
- card-orders
/card-pin-orders:
get:
description: Returns paginated card pin orders with optional filters
parameters:
- description: Filter by status
in: query
name: status
type: string
- description: Filter by branch ID
in: query
name: branch_id
type: integer
- description: Filter by user ID
in: query
name: user_id
type: integer
- description: Filter by card type ID
in: query
name: card_type_id
type: integer
- description: Filter by region
in: query
name: region
type: string
- default: 1
description: Page number
in: query
name: page
type: integer
- default: 10
description: Items per page
in: query
name: limit
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List card pin orders
tags:
- card-pin-orders
post:
consumes:
- application/json
description: Creates a new card pin order
parameters:
- description: Card pin order payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/cardpinorders.CreateCardPinOrderDTO'
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Create card pin order
tags:
- card-pin-orders
/card-pin-orders/{id}:
delete:
description: Deletes a card pin order
parameters:
- description: Card pin order ID
in: path
name: id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Delete card pin order
tags:
- card-pin-orders
get:
description: Returns a single card pin order
parameters:
- description: Card pin order ID
in: path
name: id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Get card pin order by ID
tags:
- card-pin-orders
put:
consumes:
- application/json
description: Updates an existing card pin order
parameters:
- description: Card pin order ID
in: path
name: id
required: true
type: integer
- description: Card pin order payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/cardpinorders.UpdateCardPinOrderDTO'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Update card pin order
tags:
- card-pin-orders
/cards:
get:
description: Returns paginated cards with optional filters
@@ -2972,6 +3327,99 @@ paths:
summary: Update payment card active
tags:
- payment-card
/permission-users:
get:
description: Returns the authenticated user's permission-user assignments with
the related user and permission
parameters:
- description: Filter by permission name
in: query
name: permission_name
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List permission users
tags:
- permission-users
post:
consumes:
- application/json
description: Creates a permission-user assignment
parameters:
- description: Permission-user payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/permissionuser.CreatePermissionUserDTO'
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Assign user to permission
tags:
- permission-users
/permission-users/{id}:
delete:
description: Deletes a permission-user assignment
parameters:
- description: Permission-user ID
in: path
name: id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Remove user from permission
tags:
- permission-users
/permissions:
get:
description: Returns paginated permissions with optional filters
@@ -3173,9 +3621,67 @@ paths:
summary: Get profile
tags:
- auth
put:
consumes:
- application/json
description: Updates the authenticated user's profile
parameters:
- description: Profile payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/auth.UpdateProfileDTO'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Update profile
tags:
- auth
/provinces:
get:
description: Returns all provinces
description: Returns paginated provinces with optional filters
parameters:
- description: Filter by province name (en, ru, tm)
in: query
name: name
type: string
- description: Filter by region (en, ru, tm)
in: query
name: region
type: string
- description: Filter by active status
in: query
name: active
type: boolean
- default: 1
description: Page number
in: query
name: page
type: integer
- default: 10
description: Items per page
in: query
name: limit
type: integer
produces:
- application/json
responses:
@@ -3506,6 +4012,99 @@ paths:
summary: Update reason card
tags:
- reason-card
/role-users:
get:
description: Returns the authenticated user's role-user assignments with the
related user and role
parameters:
- description: Filter by role name
in: query
name: role_name
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List role users
tags:
- role-users
post:
consumes:
- application/json
description: Creates a role-user assignment
parameters:
- description: Role-user payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/roleusers.CreateRoleUserDTO'
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Assign user to role
tags:
- role-users
/role-users/{id}:
delete:
description: Deletes a role-user assignment
parameters:
- description: Role-user ID
in: path
name: id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Remove user from role
tags:
- role-users
/roles:
get:
description: Returns paginated roles with optional filters
@@ -3884,6 +4483,53 @@ paths:
summary: Update user
tags:
- user
/users/role:
get:
description: Returns paginated users filtered by role
parameters:
- description: user role
in: query
name: role
required: true
type: string
- description: Filter by username
in: query
name: username
type: string
- default: 1
description: Page number
in: query
name: page
type: integer
- default: 10
description: Items per page
in: query
name: limit
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List users by role
tags:
- user
securityDefinitions:
BearerAuth:
in: header

View File

@@ -10,11 +10,27 @@ var swaggerTagOrder = []struct {
{Name: "auth", Description: "Authentication"},
{Name: "province", Description: "Provinces"},
{Name: "branches", Description: "Branches"},
{Name: "branch-users", Description: "Branch users"},
{Name: "user", Description: "Users"},
{Name: "role", Description: "Roles"},
{Name: "role-users", Description: "Role users"},
{Name: "permission", Description: "Permissions"},
{Name: "permission-users", Description: "Permission users"},
{Name: "payment-card", Description: "Payment cards"},
{Name: "reason-card", Description: "Reason cards"},
{Name: "cards", Description: "Cards"},
{Name: "card-orders", Description: "Card orders"},
{Name: "card-pin-orders", Description: "Card pin orders"},
{Name: "loan-type", Description: "Loan types"},
{Name: "loan-document", Description: "Loan required documents"},
{Name: "loan-orders", Description: "Loan orders"},
{Name: "loans-repayment", Description: "Loan repayments"},
{Name: "loan-paid-off-letters", Description: "Loan paid-off letters"},
{Name: "file-upload", Description: "File upload"},
}
func init() {
applySwaggerTagOrder()
}
func applySwaggerTagOrder() {

Binary file not shown.

View File

@@ -1,242 +0,0 @@
package user
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 = "/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.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List users
// @Description Returns paginated users with optional filters
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create user
// @Description Creates a new user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateUserDTO true "User payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users [post]
func (h *handler) create(c *gin.Context) {
var dto CreateUserDTO
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 user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update user
// @Description Updates an existing user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Param body body UpdateUserDTO true "User payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete user
// @Description Deletes a user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /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 user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("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
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
filter.Username = raw
}
return filter, true
}

View File

@@ -5,20 +5,24 @@ import (
"fmt"
"strings"
"online-back/internal/admin/cardorder"
"online-back/internal/cards/cardorder"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[cardorder.CardOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "card_orders", cardOrderColumnsSQL, scanCardOrder),
logger: logger,
}
}
// cardOrderWritableColumns lists every card_orders column except id, created_at and
@@ -75,37 +79,10 @@ func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM card_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM card_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
defer rows.Close()
var items []cardorder.CardOrderDTO
for rows.Next() {
item, err := scanCardOrder(rows)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
}
@@ -151,12 +128,7 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM card_orders WHERE id = $1`, cardOrderColumnsSQL)
item, err := scanCardOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return cardorder.CardOrderDTO{}, err
}
return item, nil
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
@@ -197,21 +169,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM card_orders WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCardOrder(row scannable) (cardorder.CardOrderDTO, error) {
func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
var item cardorder.CardOrderDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId,

View File

@@ -5,20 +5,24 @@ import (
"fmt"
"strings"
"online-back/internal/admin/cardpinorders"
"online-back/internal/cards/cardpinorders"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[cardpinorders.CardPinOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder),
logger: logger,
}
}
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
@@ -57,37 +61,10 @@ func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM card_pin_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM card_pin_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardPinOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
defer rows.Close()
var items []cardpinorders.CardPinOrderDTO
for rows.Next() {
item, err := scanCardPinOrder(rows)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
}
@@ -128,12 +105,7 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM card_pin_orders WHERE id = $1`, cardPinOrderColumnsSQL)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
@@ -174,21 +146,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM card_pin_orders WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCardPinOrder(row scannable) (cardpinorders.CardPinOrderDTO, error) {
func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
var item cardpinorders.CardPinOrderDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &item.Region, &item.BranchId,

View File

@@ -5,20 +5,24 @@ import (
"fmt"
"strings"
"online-back/internal/admin/cards"
"online-back/internal/cards/cards"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[cards.CardDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cards.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "cards", cardColumnsSQL, scanCard),
logger: logger,
}
}
// cardWritableColumns lists every cards column except id, created_at and
@@ -48,37 +52,10 @@ func updateArgs(dto cards.UpdateCardDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM cards` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cards.ListCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM cards%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cards.ListCardDTO{}, err
}
defer rows.Close()
var items []cards.CardDTO
for rows.Next() {
item, err := scanCard(rows)
if err != nil {
return cards.ListCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cards.ListCardDTO{}, err
}
return cards.ListCardDTO{Count: count, Cards: items}, nil
}
@@ -104,12 +81,7 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
}
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM cards WHERE id = $1`, cardColumnsSQL)
item, err := scanCard(r.client.QueryRow(ctx, query, id))
if err != nil {
return cards.CardDTO{}, err
}
return item, nil
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
@@ -150,21 +122,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM cards WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCard(row scannable) (cards.CardDTO, error) {
func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) {
var item cards.CardDTO
err := row.Scan(
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,

View File

@@ -7,20 +7,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/paymentcard"
"online-back/internal/cards/paymentcard"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[paymentcard.PaymentCardDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "card_types c", cardColumns, scanPaymentCard),
logger: logger,
}
}
const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
@@ -28,45 +34,17 @@ const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
const cardReturningColumns = `id, price, name, notes, active`
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
defer rows.Close()
var items []paymentcard.PaymentCardDTO
for rows.Next() {
item, err := scanPaymentCard(rows)
if err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
}
func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM card_types c`
func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.CardName != "" {
@@ -83,10 +61,10 @@ func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause stri
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -97,12 +75,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM card_types c WHERE c.id = $1`, cardColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return paymentcard.PaymentCardDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
@@ -157,25 +130,14 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (p
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM card_types WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) {
func scanPaymentCard(row genericrepo.Scanner) (paymentcard.PaymentCardDTO, error) {
var item paymentcard.PaymentCardDTO
var nameJSON []byte

View File

@@ -7,20 +7,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/reasonscard"
"online-back/internal/cards/reasonscard"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[reasonscard.ReasonCardDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "card_states r", reasonColumns, scanReasonCard),
logger: logger,
}
}
const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r.updated_at`
@@ -28,45 +34,17 @@ const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r
const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
reasonColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
defer rows.Close()
var items []reasonscard.ReasonCardDTO
for rows.Next() {
item, err := scanReasonCard(rows)
if err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
}
func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM card_states r`
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.ReasonName != "" {
args = append(args, likePattern(filter.ReasonName))
@@ -77,10 +55,10 @@ func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause stri
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -91,12 +69,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM card_states r WHERE r.id = $1`, reasonColumns)
item, err := scanReasonCard(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return reasonscard.ReasonCardDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
@@ -139,25 +112,14 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM card_states WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanReasonCard(row scannable) (reasonscard.ReasonCardDTO, error) {
func scanReasonCard(row genericrepo.Scanner) (reasonscard.ReasonCardDTO, error) {
var item reasonscard.ReasonCardDTO
var nameJSON []byte

39
internal/cards/router.go Normal file
View File

@@ -0,0 +1,39 @@
// Package cards groups payment cards, card orders, PIN orders, and their
// reference data (reasons, payment card types) under one bounded context,
// replacing the flat internal/admin/* listing.
package cards
import (
"online-back/internal/cards/cardorder"
cardorderdb "online-back/internal/cards/cardorder/db"
"online-back/internal/cards/cardpinorders"
cardpinordersdb "online-back/internal/cards/cardpinorders/db"
cardentity "online-back/internal/cards/cards"
cardentitydb "online-back/internal/cards/cards/db"
"online-back/internal/cards/paymentcard"
paymentcarddb "online-back/internal/cards/paymentcard/db"
"online-back/internal/cards/reasonscard"
reasonscarddb "online-back/internal/cards/reasonscard/db"
"online-back/internal/handlers"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// Register wires every cards module's handler onto router.
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
for _, h := range Handlers(client, logger) {
h.Register(router)
}
}
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)),
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
}
}

View File

@@ -3,40 +3,11 @@ package handlermanager
import (
"net/http"
"online-back/internal/admin/auth"
authdb "online-back/internal/admin/auth/db"
"online-back/internal/admin/branches"
branchesdb "online-back/internal/admin/branches/db"
"online-back/internal/admin/cardorder"
cardorderdb "online-back/internal/admin/cardorder/db"
"online-back/internal/admin/cardpinorders"
cardpinordersdb "online-back/internal/admin/cardpinorders/db"
"online-back/internal/admin/cards"
cardsdb "online-back/internal/admin/cards/db"
"online-back/internal/admin/loanorders"
loanordersdb "online-back/internal/admin/loanorders/db"
"online-back/internal/admin/loanpaidletter"
loanpaidletterdb "online-back/internal/admin/loanpaidletter/db"
"online-back/internal/admin/loansdocument"
loansdocumentdb "online-back/internal/admin/loansdocument/db"
"online-back/internal/admin/loansrepayment"
loansrepaymentdb "online-back/internal/admin/loansrepayment/db"
"online-back/internal/admin/loantype"
loantypedb "online-back/internal/admin/loantype/db"
"online-back/internal/admin/paymentcard"
paymentcarddb "online-back/internal/admin/paymentcard/db"
"online-back/internal/admin/permission"
permissiondb "online-back/internal/admin/permission/db"
"online-back/internal/admin/province"
provincedb "online-back/internal/admin/province/db"
"online-back/internal/admin/reasonscard"
reasonscarddb "online-back/internal/admin/reasonscard/db"
"online-back/internal/admin/role"
roledb "online-back/internal/admin/role/db"
"online-back/internal/admin/user"
userdb "online-back/internal/admin/user/db"
"online-back/internal/cards"
"online-back/internal/config"
"online-back/internal/handlers"
"online-back/internal/identity"
"online-back/internal/lending"
"online-back/internal/org"
"online-back/pkg/logging"
"github.com/gin-contrib/cors"
@@ -70,32 +41,13 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
}))
adminGroup := router.Group(adminAPIPrefix)
for _, h := range adminHandlers(client, logger) {
h.Register(adminGroup)
}
// Each bounded context registers its own modules' handlers.
// Add new modules inside the relevant context's router.go rather than here.
identity.Register(adminGroup, client, logger)
org.Register(adminGroup, client, logger)
lending.Register(adminGroup, client, logger)
cards.Register(adminGroup, client, logger)
return router
}
// adminHandlers builds every handlers.Handler registered under adminAPIPrefix.
// Add new modules here rather than inlining their wiring into New.
func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
province.NewHandler(logger, provincedb.NewRepository(client, logger)),
branches.NewHandler(logger, branchesdb.NewRepository(client, logger)),
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
cards.NewHandler(logger, cardsdb.NewRepository(client, logger)),
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)),
loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)),
loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)),
role.NewHandler(logger, roledb.NewRepository(client, logger)),
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
user.NewHandler(logger, userdb.NewRepository(client, logger)),
}
}

View File

@@ -2,9 +2,9 @@ package db
import (
"context"
"encoding/json"
"errors"
"online-back/internal/admin/auth"
"online-back/internal/identity/auth"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -56,41 +56,28 @@ func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDT
return profile, err
}
const (
createBranchUserQuery = `
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, inserted.created_at, inserted.updated_at
FROM inserted
JOIN branches b ON b.id = inserted.branch_id`
deleteBranchUserQuery = `DELETE FROM branch_user WHERE id = $1`
)
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`
func (r *repository) CreateBranchUser(ctx context.Context, dto auth.CreateBranchUserDTO) (auth.BranchUserDTO, error) {
var item auth.BranchUserDTO
var branchNameJSON []byte
err := r.client.QueryRow(ctx, createBranchUserQuery, dto.BranchId, dto.UserId).Scan(
&item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.CreatedAt, &item.UpdatedAt,
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,
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
if err != nil {
return auth.BranchUserDTO{}, err
if errors.Is(err, pgx.ErrNoRows) {
return auth.UserProfileDTO{}, err
}
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
return auth.BranchUserDTO{}, err
}
return item, nil
}
func (r *repository) DeleteBranchUser(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, deleteBranchUserQuery, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return profile, err
}

View File

@@ -21,27 +21,15 @@ type UserProfileDTO struct {
CreatedAt time.Time `json:"createdAt"`
}
type UpdateProfileDTO struct {
Name string `json:"name" binding:"required"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
}
type UserCredentials struct {
Id int
Password string
}
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type BranchUserDTO struct {
Id int64 `json:"id"`
BranchId int64 `json:"branchId"`
BranchName LocalizedText `json:"branchName"`
UserId int64 `json:"userId"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateBranchUserDTO struct {
BranchId int64 `json:"branchId" binding:"required"`
UserId int64 `json:"userId" binding:"required"`
}

186
internal/identity/auth/handler.go Executable file
View File

@@ -0,0 +1,186 @@
package auth
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
)
type handler struct {
logger *logging.Logger
repository Repository
service *Service
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository, service: NewService(repository)}
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
protected.PUT(profileURL, h.updateProfile)
}
// login godoc
// @Summary Login
// @Description Authenticates a user by email and password
// @Tags auth
// @Accept json
// @Produce json
// @Param body body LoginDTO true "Login payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) {
var dto LoginDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.Login(c.Request.Context(), dto)
if errors.Is(err, ErrInvalidCredentials) {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// refreshToken godoc
// @Summary Refresh tokens
// @Description Issues a new access and refresh token pair
// @Tags auth
// @Accept json
// @Produce json
// @Param body body RefreshTokenDTO true "Refresh token payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /token [post]
func (h *handler) refreshToken(c *gin.Context) {
var dto RefreshTokenDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.RefreshToken(c.Request.Context(), dto.RefreshToken)
if errors.Is(err, ErrInvalidCredentials) {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Tags auth
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [get]
func (h *handler) getProfile(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
if err != nil {
h.logger.Errorf("get profile failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
// updateProfile godoc
// @Summary Update profile
// @Description Updates the authenticated user's profile
// @Tags auth
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body UpdateProfileDTO true "Profile payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [put]
func (h *handler) updateProfile(c *gin.Context) {
userID, ok := currentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
var dto UpdateProfileDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
profile, err := h.repository.UpdateProfile(c.Request.Context(), userID, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update profile failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
func currentUserID(c *gin.Context) (int, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int:
return id, id > 0
case string:
parsed, err := strconv.Atoi(id)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}

View File

@@ -0,0 +1,55 @@
package auth
import (
"context"
"errors"
"online-back/pkg/utils"
"golang.org/x/crypto/bcrypt"
)
// ErrInvalidCredentials covers both "no such user" and "wrong password" for
// login, and any refresh-token validation failure — callers map it to 401.
// Any other error from these methods (token generation failure) maps to 400.
var ErrInvalidCredentials = errors.New("invalid credentials")
type Service struct {
repository Repository
}
func NewService(repository Repository) *Service {
return &Service{repository: repository}
}
func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) {
user, err := s.repository.Login(ctx, dto)
if err != nil {
return nil, ErrInvalidCredentials
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
return nil, ErrInvalidCredentials
}
return utils.GenerateTokenPair(user.Id)
}
func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[string]string, error) {
claims, err := utils.ParseRefreshToken(refreshToken)
if err != nil {
return nil, ErrInvalidCredentials
}
id, ok := utils.ClaimID(claims)
if !ok {
return nil, ErrInvalidCredentials
}
user, err := s.repository.GetUserByID(ctx, id)
if err != nil || user.Id != id {
return nil, ErrInvalidCredentials
}
return utils.GenerateTokenPair(id)
}

View File

@@ -6,6 +6,5 @@ type Repository interface {
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
CreateBranchUser(ctx context.Context, dto CreateBranchUserDTO) (BranchUserDTO, error)
DeleteBranchUser(ctx context.Context, id int64) error
UpdateProfile(ctx context.Context, id int, dto UpdateProfileDTO) (UserProfileDTO, error)
}

View File

@@ -6,20 +6,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/permission"
"online-back/internal/identity/permission"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[permission.PermissionDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission),
logger: logger,
}
}
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
@@ -27,45 +33,17 @@ const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.u
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return permission.ListPermissionDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY p.id LIMIT $%d OFFSET $%d`,
permissionColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return permission.ListPermissionDTO{}, err
}
defer rows.Close()
var items []permission.PermissionDTO
for rows.Next() {
item, err := scanPermission(rows)
if err != nil {
return permission.ListPermissionDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return permission.ListPermissionDTO{}, err
}
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
}
func buildListQuery(filter permission.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM permissions p`
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName))
@@ -74,10 +52,10 @@ func buildListQuery(filter permission.ListFilter) (fromClause, whereClause strin
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -88,12 +66,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM permissions p WHERE p.id = $1`, permissionColumns)
item, err := scanPermission(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return permission.PermissionDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
@@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto permission.Update
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permissions WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermission(row scannable) (permission.PermissionDTO, error) {
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
var item permission.PermissionDTO
if err := row.Scan(
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,

View File

@@ -0,0 +1,132 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/permissionuser"
"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) permissionuser.Repository {
return &repository{client: client, logger: logger}
}
const permissionUserFromClause = ` FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
JOIN users u ON u.id = pu.user_id`
const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at`
func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
defer rows.Close()
var items []permissionuser.PermissionUserDTO
for rows.Next() {
item, err := scanPermissionUser(rows)
if err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return permissionuser.ListPermissionUserDTO{}, err
}
return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil
}
func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args)))
}
if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName))
conditions = append(conditions, fmt.Sprintf("p.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 permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
query := `
WITH inserted AS (
INSERT INTO permission_user (permission_id, user_id)
VALUES ($1, $2)
RETURNING id, permission_id, user_id, created_at, updated_at
)
SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
FROM inserted
JOIN permissions p ON p.id = inserted.permission_id
JOIN users u ON u.id = inserted.user_id`
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId)
return scanPermissionUser(row)
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_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 scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
var item permissionuser.PermissionUserDTO
err := row.Scan(
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return permissionuser.PermissionUserDTO{}, err
}
if err != nil {
return permissionuser.PermissionUserDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,28 @@
package permissionuser
import "time"
type PermissionUserDTO struct {
Id int64 `json:"id"`
UserId int64 `json:"userId"`
UserName string `json:"userName"`
PermissionId int64 `json:"permissionId"`
PermissionName string `json:"permissionName"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type ListPermissionUserDTO struct {
Count int64 `json:"count"`
Items []PermissionUserDTO `json:"items"`
}
type ListFilter struct {
UserId *int64
PermissionName string
}
type CreatePermissionUserDTO struct {
PermissionId int64 `json:"permissionId" binding:"required"`
UserId int64 `json:"userId" binding:"required"`
}

View File

@@ -0,0 +1,152 @@
package permissionuser
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 = "/permission-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 permission users
// @Description Returns the authenticated user's permission-user assignments with the related user and permission
// @Tags permission-users
// @Produce json
// @Security BearerAuth
// @Param permission_name query string false "Filter by permission name"
// @Success 200 {object} appresult.AppSuccess
// @Failure 401 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-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,
PermissionName: strings.TrimSpace(c.Query("permission_name")),
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list permission users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// create godoc
// @Summary Assign user to permission
// @Description Creates a permission-user assignment
// @Tags permission-users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users [post]
func (h *handler) create(c *gin.Context) {
var dto CreatePermissionUserDTO
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 permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Remove user from permission
// @Description Deletes a permission-user assignment
// @Tags permission-users
// @Produce json
// @Security BearerAuth
// @Param id path int true "Permission-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-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 permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("permission 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 permissionuser
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error)
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,38 @@
package rbac
import (
"net/http"
"strconv"
"online-back/internal/appresult"
"github.com/gin-gonic/gin"
)
// RequirePermission returns a gin middleware that 403s unless the
// authenticated user (set by appresult.JwtTokenCheck, which must run first)
// has been directly granted the given permission code. Not currently
// attached to any route.
func RequirePermission(service *Service, code string) gin.HandlerFunc {
return func(c *gin.Context) {
rawID, exists := c.Get("id")
if !exists {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
return
}
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
if err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
return
}
granted, err := service.HasPermission(c.Request.Context(), userID, code)
if err != nil || !granted {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
return
}
c.Next()
}
}

View File

@@ -0,0 +1,42 @@
// Package rbac provides permission-check capability on top of the existing
// permissions/permission_user tables. It is not wired into any route yet —
// today every route is still gated only by appresult.JwtTokenCheck()'s
// admin-claim check. RequirePermission is available for routes to opt into
// once permission data is populated and specific routes are chosen.
//
// Note: the schema has no role_permission pivot table, so role-based
// permission resolution isn't possible yet — HasPermission only resolves
// permissions granted directly via permission_user.
package rbac
import (
"context"
"online-back/pkg/client/postgresql"
)
type Service struct {
client postgresql.Client
}
func NewService(client postgresql.Client) *Service {
return &Service{client: client}
}
// HasPermission reports whether userID has been directly granted the
// permission identified by code (permissions.code) via permission_user.
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2
)`
var granted bool
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
return false, err
}
return granted, nil
}

View File

@@ -0,0 +1,56 @@
package rbac
import (
"context"
"testing"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type fakeClient struct {
granted bool
}
func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
return nil, nil
}
func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
return nil, nil
}
func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
return fakeRow{granted: f.granted}
}
func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) {
return nil, nil
}
type fakeRow struct {
granted bool
}
func (r fakeRow) Scan(dest ...interface{}) error {
*dest[0].(*bool) = r.granted
return nil
}
func TestHasPermission(t *testing.T) {
granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !granted {
t.Fatal("expected permission to be granted")
}
granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if granted {
t.Fatal("expected permission to not be granted")
}
}

View File

@@ -6,20 +6,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/role"
"online-back/internal/identity/role"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[role.RoleDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "roles r", roleColumns, scanRole),
logger: logger,
}
}
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
@@ -27,45 +33,17 @@ const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return role.ListRoleDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return role.ListRoleDTO{}, err
}
defer rows.Close()
var items []role.RoleDTO
for rows.Next() {
item, err := scanRole(rows)
if err != nil {
return role.ListRoleDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return role.ListRoleDTO{}, err
}
return role.ListRoleDTO{Count: count, Roles: items}, nil
}
func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM roles r`
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.RoleName != "" {
args = append(args, likePattern(filter.RoleName))
@@ -74,10 +52,10 @@ func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, arg
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -88,12 +66,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns)
item, err := scanRole(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return role.RoleDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
@@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDT
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM roles WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanRole(row scannable) (role.RoleDTO, error) {
func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) {
var item role.RoleDTO
if err := row.Scan(
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,

View File

@@ -0,0 +1,132 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/roleusers"
"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) roleusers.Repository {
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)
RETURNING id, role_id, user_id, created_at, updated_at
)
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`
row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId)
return scanRoleUser(row)
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM role_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 scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) {
var item roleusers.RoleUserDTO
err := row.Scan(
&item.Id, &item.RoleId, &item.RoleName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return roleusers.RoleUserDTO{}, err
}
if err != nil {
return roleusers.RoleUserDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,28 @@
package roleusers
import "time"
type RoleUserDTO struct {
Id int64 `json:"id"`
UserId int64 `json:"userId"`
UserName string `json:"userName"`
RoleId int64 `json:"roleId"`
RoleName string `json:"roleName"`
CreatedAt time.Time `json:"createdAt"`
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"`
}

View File

@@ -0,0 +1,152 @@
package roleusers
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 = "/role-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 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
// @Tags role-users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateRoleUserDTO true "Role-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /role-users [post]
func (h *handler) create(c *gin.Context) {
var dto CreateRoleUserDTO
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 role user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Remove user from role
// @Description Deletes a role-user assignment
// @Tags role-users
// @Produce json
// @Security BearerAuth
// @Param id path int true "Role-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /role-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 role user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("role 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 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
}

View File

@@ -0,0 +1,45 @@
// Package identity groups authentication, users, and RBAC (roles,
// permissions, and their user/branch assignments) under one bounded
// context, replacing the flat internal/admin/* listing.
package identity
import (
"online-back/internal/handlers"
"online-back/internal/identity/auth"
authdb "online-back/internal/identity/auth/db"
"online-back/internal/identity/permission"
permissiondb "online-back/internal/identity/permission/db"
"online-back/internal/identity/permissionuser"
permissionuserdb "online-back/internal/identity/permissionuser/db"
"online-back/internal/identity/role"
roledb "online-back/internal/identity/role/db"
"online-back/internal/identity/roleusers"
roleusersdb "online-back/internal/identity/roleusers/db"
"online-back/internal/identity/user"
userdb "online-back/internal/identity/user/db"
"online-back/internal/identity/userbranch"
userbranchdb "online-back/internal/identity/userbranch/db"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// Register wires every identity module's handler onto router.
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
for _, h := range Handlers(client, logger) {
h.Register(router)
}
}
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
user.NewHandler(logger, userdb.NewRepository(client, logger)),
role.NewHandler(logger, roledb.NewRepository(client, logger)),
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
}
}

View File

@@ -7,7 +7,7 @@ import (
"fmt"
"strings"
"online-back/internal/admin/user"
"online-back/internal/identity/user"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -66,7 +66,11 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis
}
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM users u`
return buildFilteredListQuery(filter, "")
}
func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM users u `
var conditions []string
if filter.Username != "" {
@@ -74,6 +78,11 @@ func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, arg
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
}
if role != "" {
args = append(args, role)
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
}
if len(conditions) == 0 {
return fromClause, "", args
@@ -89,6 +98,43 @@ func likePattern(term string) string {
return "%" + term + "%"
}
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return user.ListUserDTO{}, err
}
defer rows.Close()
var items []user.UserDTO
for rows.Next() {
item, err := scanUser(rows)
if err != nil {
return user.ListUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return user.ListUserDTO{}, err
}
return user.ListUserDTO{Count: count, Users: items}, nil
}
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
item, err := scanUser(r.client.QueryRow(ctx, query, id))

View File

@@ -1,4 +1,4 @@
package auth
package user
import (
"context"
@@ -8,6 +8,7 @@ import (
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"online-back/internal/appresult"
@@ -15,19 +16,14 @@ import (
"online-back/internal/handlers"
"online-back/pkg/logging"
minioUpload "online-back/pkg/minio"
"online-back/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
"github.com/minio/minio-go/v7"
"golang.org/x/crypto/bcrypt"
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
branchUserURL = "/branch-users"
baseURL = "/users"
fileUploadURL = "/file"
fileURL = "/file/:id"
)
@@ -42,154 +38,150 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/role", h.listUsersByRole)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
protected.POST(fileUploadURL, h.fileUpload)
protected.GET(fileURL, h.getFile)
protected.DELETE(fileURL, h.deleteFile)
branchUserGroup := router.Group(branchUserURL, appresult.JwtTokenCheck())
branchUserGroup.POST("", h.createBranchUser)
branchUserGroup.DELETE("/:id", h.deleteBranchUser)
// Avatar/profile file storage — kept at the top-level /file path (not
// nested under /users) to preserve the existing API contract; this used
// to live in the auth handler purely incidentally.
files := router.Group("", appresult.JwtTokenCheck())
files.POST(fileUploadURL, h.fileUpload)
files.GET(fileURL, h.getFile)
files.DELETE(fileURL, h.deleteFile)
}
// login godoc
// @Summary Login
// @Description Authenticates a user by email and password
// @Tags auth
// @Accept json
// @Produce json
// @Param body body LoginDTO true "Login payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) {
var dto LoginDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
user, err := h.repository.Login(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("login lookup failed: %v", err)
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(user.Id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// refreshToken godoc
// @Summary Refresh tokens
// @Description Issues a new access and refresh token pair
// @Tags auth
// @Accept json
// @Produce json
// @Param body body RefreshTokenDTO true "Refresh token payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /token [post]
func (h *handler) refreshToken(c *gin.Context) {
var dto RefreshTokenDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
if err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
id, ok := utils.ClaimID(claims)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
user, err := h.repository.GetUserByID(c.Request.Context(), id)
if err != nil || user.Id != id {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Tags auth
// list godoc
// @Summary List users
// @Description Returns paginated users with optional filters
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [get]
func (h *handler) getProfile(c *gin.Context) {
userID, ok := currentUserID(c)
// @Failure 500 {object} appresult.AppError
// @Router /users [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("get profile failed: %v", err)
h.logger.Errorf("list users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listUsersByRole godoc
// @Summary List users by role
// @Description Returns paginated users filtered by role
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param role query string true "user role"
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/role [get]
func (h *handler) listUsersByRole(c *gin.Context) {
role := strings.TrimSpace(c.Query("role"))
if role == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByRole(c.Request.Context(), role, filter)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// createBranchUser godoc
// @Summary Assign user to branch
// @Description Creates a branch-user assignment
// @Tags auth
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create user
// @Description Creates a new user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateBranchUserDTO true "Branch-user payload"
// @Param body body CreateUserDTO true "User payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branch-users [post]
func (h *handler) createBranchUser(c *gin.Context) {
var dto CreateBranchUserDTO
// @Router /users [post]
func (h *handler) create(c *gin.Context) {
var dto CreateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.CreateBranchUser(c.Request.Context(), dto)
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create branch user failed: %v", err)
h.logger.Errorf("create user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
@@ -197,35 +189,76 @@ func (h *handler) createBranchUser(c *gin.Context) {
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// deleteBranchUser godoc
// @Summary Remove user from branch
// @Description Deletes a branch-user assignment
// @Tags auth
// update godoc
// @Summary Update user
// @Description Updates an existing user
// @Tags user
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch-user ID"
// @Param id path int true "User ID"
// @Param body body UpdateUserDTO true "User payload"
// @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) deleteBranchUser(c *gin.Context) {
// @Router /users/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.DeleteBranchUser(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
var dto UpdateUserDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if 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)
}
if err != nil {
h.logger.Errorf("update user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed"))
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete user
// @Description Deletes a user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param id path int true "User ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /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 user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
}
func parseID(raw string) (int64, bool) {
@@ -236,21 +269,39 @@ func parseID(raw string) (int64, bool) {
return id, true
}
func currentUserID(c *gin.Context) (int, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
switch id := rawID.(type) {
case int:
return id, id > 0
case string:
parsed, err := strconv.Atoi(id)
return parsed, err == nil && parsed > 0
default:
return 0, false
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
filter.Username = raw
}
return filter, true
}
// fileUpload godoc

View File

@@ -5,6 +5,7 @@ import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
GetByID(ctx context.Context, id int64) (UserDTO, error)
GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error)
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
Delete(ctx context.Context, id int64) error

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
}

View File

@@ -5,20 +5,24 @@ import (
"fmt"
"strings"
"online-back/internal/admin/loanorders"
"online-back/internal/lending/loanorders"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[loanorders.LoanOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loanorders.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "loan_orders", loanOrderColumnsSQL, scanLoanOrder),
logger: logger,
}
}
// loanOrderWritableColumns lists every loan_orders column except id, created_at and
@@ -95,37 +99,10 @@ func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter loanorders.ListFilter) (loanorders.ListLoanOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM loan_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return loanorders.ListLoanOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM loan_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
loanOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
if err != nil {
return loanorders.ListLoanOrderDTO{}, err
}
defer rows.Close()
var items []loanorders.LoanOrderDTO
for rows.Next() {
item, err := scanLoanOrder(rows)
if err != nil {
return loanorders.ListLoanOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loanorders.ListLoanOrderDTO{}, err
}
return loanorders.ListLoanOrderDTO{Count: count, LoanOrders: items}, nil
}
@@ -161,12 +138,7 @@ func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []in
}
func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_orders WHERE id = $1`, loanOrderColumnsSQL)
item, err := scanLoanOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return loanorders.LoanOrderDTO{}, err
}
return item, nil
return r.generic.GetByID(ctx, id)
}
// nextUniqueIDSQL computes unique_id as the last value stored in loan_orders plus
@@ -213,21 +185,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanorders.Update
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_orders WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanOrder(row scannable) (loanorders.LoanOrderDTO, error) {
func scanLoanOrder(row genericrepo.Scanner) (loanorders.LoanOrderDTO, error) {
var item loanorders.LoanOrderDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.Source, &item.UserId, &item.LoanType, &item.Region, &item.BranchId,

View File

@@ -5,20 +5,24 @@ import (
"fmt"
"strings"
"online-back/internal/admin/loanpaidletter"
"online-back/internal/lending/loanpaidletter"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[loanpaidletter.LoanPaidLetterDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loanpaidletter.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "loan_paid_off_letters", letterColumnsSQL, scanLoanPaidLetter),
logger: logger,
}
}
// letterWritableColumns lists every loan_paid_off_letters column except id, created_at
@@ -60,37 +64,10 @@ func updateArgs(dto loanpaidletter.UpdateLoanPaidLetterDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter) (loanpaidletter.ListLoanPaidLetterDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM loan_paid_off_letters` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM loan_paid_off_letters%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
letterColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
if err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
defer rows.Close()
var items []loanpaidletter.LoanPaidLetterDTO
for rows.Next() {
item, err := scanLoanPaidLetter(rows)
if err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil
}
@@ -133,12 +110,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_paid_off_letters WHERE id = $1`, letterColumnsSQL)
item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, id))
if err != nil {
return loanpaidletter.LoanPaidLetterDTO{}, err
}
return item, nil
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
@@ -179,21 +151,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.Up
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_paid_off_letters WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanPaidLetter(row scannable) (loanpaidletter.LoanPaidLetterDTO, error) {
func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) {
var item loanpaidletter.LoanPaidLetterDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId,

View File

@@ -6,20 +6,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/loansdocument"
"online-back/internal/lending/loansdocument"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[loansdocument.LoanDocumentDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loansdocument.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "loan_order_required_docs d", documentColumns, scanLoanDocument),
logger: logger,
}
}
const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.updated_at`
@@ -27,45 +33,17 @@ const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.update
const documentReturningColumns = `id, name, value, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return loansdocument.ListLoanDocumentDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY d.id LIMIT $%d OFFSET $%d`,
documentColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return loansdocument.ListLoanDocumentDTO{}, err
}
defer rows.Close()
var items []loansdocument.LoanDocumentDTO
for rows.Next() {
item, err := scanLoanDocument(rows)
if err != nil {
return loansdocument.ListLoanDocumentDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loansdocument.ListLoanDocumentDTO{}, err
}
return loansdocument.ListLoanDocumentDTO{Count: count, LoansDocuments: items}, nil
}
func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM loan_order_required_docs d`
func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.DocumentName != "" {
@@ -80,10 +58,10 @@ func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause st
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -94,12 +72,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_order_required_docs d WHERE d.id = $1`, documentColumns)
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return loansdocument.LoanDocumentDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
@@ -147,21 +120,10 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (l
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_order_required_docs WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanDocument(row scannable) (loansdocument.LoanDocumentDTO, error) {
func scanLoanDocument(row genericrepo.Scanner) (loansdocument.LoanDocumentDTO, error) {
var item loansdocument.LoanDocumentDTO
if err := row.Scan(

View File

@@ -6,20 +6,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/loansrepayment"
"online-back/internal/lending/loansrepayment"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[loansrepayment.LoanRepaymentDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loansrepayment.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "loans l", loanColumns, scanLoanRepayment),
logger: logger,
}
}
const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account_number, l.created_at, l.updated_at`
@@ -27,45 +33,17 @@ const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account
const loanReturningColumns = `id, user_id, passport_serie, passport_id, account_number, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter) (loansrepayment.ListLoanRepaymentDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`,
loanColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
defer rows.Close()
var items []loansrepayment.LoanRepaymentDTO
for rows.Next() {
item, err := scanLoanRepayment(rows)
if err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
return loansrepayment.ListLoanRepaymentDTO{Count: count, Loans: items}, nil
}
func buildListQuery(filter loansrepayment.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM loans l`
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PassportId != "" {
args = append(args, likePattern(filter.PassportId))
@@ -73,10 +51,10 @@ func buildListQuery(filter loansrepayment.ListFilter) (fromClause, whereClause s
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -87,12 +65,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loans l WHERE l.id = $1`, loanColumns)
item, err := scanLoanRepayment(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return loansrepayment.LoanRepaymentDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto loansrepayment.CreateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
@@ -120,21 +93,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.Up
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loans WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanRepayment(row scannable) (loansrepayment.LoanRepaymentDTO, error) {
func scanLoanRepayment(row genericrepo.Scanner) (loansrepayment.LoanRepaymentDTO, error) {
var item loansrepayment.LoanRepaymentDTO
if err := row.Scan(

View File

@@ -7,20 +7,26 @@ import (
"fmt"
"strings"
"online-back/internal/admin/loantype"
"online-back/internal/lending/loantype"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[loantype.LoanTypeDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "loan_types lt", loanTypeColumns, scanLoanType),
logger: logger,
}
}
const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.active, lt.created_at, lt.updated_at`
@@ -28,45 +34,17 @@ const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.activ
const loanTypeReturningColumns = `id, name, tax, maturity, notes, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return loantype.ListLoanTypeDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY lt.id LIMIT $%d OFFSET $%d`,
loanTypeColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return loantype.ListLoanTypeDTO{}, err
}
defer rows.Close()
var items []loantype.LoanTypeDTO
for rows.Next() {
item, err := scanLoanType(rows)
if err != nil {
return loantype.ListLoanTypeDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loantype.ListLoanTypeDTO{}, err
}
return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil
}
func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM loan_types lt`
func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.LoanTypeName != "" {
args = append(args, likePattern(filter.LoanTypeName))
@@ -77,10 +55,10 @@ func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string,
}
if len(conditions) == 0 {
return fromClause, "", args
return "", args
}
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
@@ -91,12 +69,7 @@ func likePattern(term string) string {
}
func (r *repository) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_types lt WHERE lt.id = $1`, loanTypeColumns)
item, err := scanLoanType(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return loantype.LoanTypeDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
@@ -139,14 +112,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLo
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_types WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) {
@@ -161,11 +127,7 @@ func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error)
return titleJSON, contentJSON, nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanType(row scannable) (loantype.LoanTypeDTO, error) {
func scanLoanType(row genericrepo.Scanner) (loantype.LoanTypeDTO, error) {
var item loantype.LoanTypeDTO
var nameJSON, notesJSON []byte

View File

@@ -0,0 +1,39 @@
// Package lending groups loan orders and their related documents,
// repayments, types, and paid-off letters under one bounded context,
// replacing the flat internal/admin/* listing.
package lending
import (
"online-back/internal/handlers"
"online-back/internal/lending/loanorders"
loanordersdb "online-back/internal/lending/loanorders/db"
"online-back/internal/lending/loanpaidletter"
loanpaidletterdb "online-back/internal/lending/loanpaidletter/db"
"online-back/internal/lending/loansdocument"
loansdocumentdb "online-back/internal/lending/loansdocument/db"
"online-back/internal/lending/loansrepayment"
loansrepaymentdb "online-back/internal/lending/loansrepayment/db"
"online-back/internal/lending/loantype"
loantypedb "online-back/internal/lending/loantype/db"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// Register wires every lending module's handler into router.
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
for _, h := range Handlers(client, logger) {
h.Register(router)
}
}
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)),
loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)),
loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)),
}
}

View File

@@ -7,21 +7,27 @@ import (
"fmt"
"strings"
"online-back/internal/admin/branches"
"online-back/internal/org/branches"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[branches.BranchDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "branches", branchSelectColumns, scanBranch),
logger: logger,
}
}
const branchFromClause = ` FROM branches b
@@ -148,7 +154,7 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
return branches.BranchDTO{}, err
}
name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers)
name, address, err := marshalBranchJSON(dto.Name, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
@@ -173,7 +179,7 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
LEFT JOIN provinces p ON p.id = i.province_id`
row := r.client.QueryRow(ctx, query,
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers,
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
@@ -190,7 +196,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
return branches.BranchDTO{}, err
}
name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers)
name, address, err := marshalBranchJSON(dto.Name, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
@@ -211,7 +217,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
LEFT JOIN provinces p ON p.id = u.province_id`
row := r.client.QueryRow(ctx, query,
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers,
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
dto.BillingSwiftUsername, dto.BillingSwiftPassword, dto.Active, id,
@@ -227,14 +233,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM branches WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
func (r *repository) ensureProvince(ctx context.Context, provinceID *int64) error {
@@ -251,23 +250,16 @@ func (r *repository) ensureProvince(ctx context.Context, provinceID *int64) erro
return err
}
func marshalBranchJSON(name, address branches.LocalizedText, phoneNumbers []string) ([]byte, []byte, []byte, error) {
func marshalBranchJSON(name, address branches.LocalizedText) ([]byte, []byte, error) {
nameJSON, err := json.Marshal(name)
if err != nil {
return nil, nil, nil, err
return nil, nil, err
}
addressJSON, err := json.Marshal(address)
if err != nil {
return nil, nil, nil, err
return nil, nil, err
}
if phoneNumbers == nil {
phoneNumbers = []string{}
}
phoneNumbersJSON, err := json.Marshal(phoneNumbers)
if err != nil {
return nil, nil, nil, err
}
return nameJSON, addressJSON, phoneNumbersJSON, nil
return nameJSON, addressJSON, nil
}
func nullIfEmpty(value string) interface{} {
@@ -282,18 +274,14 @@ func isUniqueViolation(err error) bool {
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanBranch(row scannable) (branches.BranchDTO, error) {
func scanBranch(row genericrepo.Scanner) (branches.BranchDTO, error) {
var item branches.BranchDTO
var nameJSON, addressJSON, provinceNameJSON, phoneNumbersJSON []byte
var nameJSON, addressJSON, provinceNameJSON []byte
var uniqueCode *string
err := row.Scan(
&item.Id, &uniqueCode, &nameJSON, &addressJSON, &item.Region, &item.ProvinceId, &provinceNameJSON,
&phoneNumbersJSON,
&item.PhoneNumbers,
&item.BillingUsername, &item.BillingPassword,
&item.BillingSberUsername, &item.BillingSberPassword,
&item.BillingVisaMasterUsername, &item.BillingVisaMasterPassword,
@@ -316,11 +304,5 @@ func scanBranch(row scannable) (branches.BranchDTO, error) {
return branches.BranchDTO{}, err
}
}
if err := json.Unmarshal(phoneNumbersJSON, &item.PhoneNumbers); err != nil {
return branches.BranchDTO{}, err
}
if item.PhoneNumbers == nil {
item.PhoneNumbers = []string{}
}
return item, nil
}

View File

@@ -14,7 +14,7 @@ type BranchDTO struct {
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName LocalizedText `json:"provinceName"`
PhoneNumbers []string `json:"phoneNumbers"`
PhoneNumbers string `json:"phoneNumbers"`
BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"`
BillingSberUsername string `json:"billingSberUsername"`
@@ -32,7 +32,7 @@ type CreateBranchDTO struct {
Address LocalizedText `json:"address" binding:"required"`
Region string `json:"region" binding:"required"`
ProvinceId *int64 `json:"provinceId"`
PhoneNumbers []string `json:"phoneNumbers"`
PhoneNumbers string `json:"phoneNumbers"`
BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"`
BillingSberUsername string `json:"billingSberUsername"`
@@ -50,7 +50,7 @@ type UpdateBranchDTO struct {
Address LocalizedText `json:"address" binding:"required"`
Region string `json:"region" binding:"required"`
ProvinceId *int64 `json:"provinceId"`
PhoneNumbers []string `json:"phoneNumbers"`
PhoneNumbers string `json:"phoneNumbers"`
BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"`
BillingSberUsername string `json:"billingSberUsername"`

View File

@@ -4,51 +4,84 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/province"
"online-back/internal/org/province"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
client postgresql.Client
generic *genericrepo.Repository[province.ProvinceDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) province.Repository {
return &repository{client: client, logger: logger}
return &repository{
client: client,
generic: genericrepo.New(client, "provinces", provinceSelectColumns, scanProvince),
logger: logger,
}
}
const provinceSelectColumns = `id, name, region, active`
func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
rows, err := r.client.Query(ctx, `SELECT `+provinceSelectColumns+` FROM provinces ORDER BY id`)
func (r *repository) List(ctx context.Context, filter province.ListFilter) (province.ListProvinceDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return nil, err
}
defer rows.Close()
var items []province.ProvinceDTO
for rows.Next() {
item, err := scanProvince(rows)
if err != nil {
return nil, err
}
items = append(items, item)
return province.ListProvinceDTO{}, err
}
return items, rows.Err()
return province.ListProvinceDTO{Count: count, Provinces: items}, nil
}
func buildListQuery(filter province.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Name != "" {
args = append(args, likePattern(filter.Name))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
name->>'en' ILIKE $%[1]d OR name->>'ru' ILIKE $%[1]d OR name->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.Region != "" {
args = append(args, likePattern(filter.Region))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
region->>'en' ILIKE $%[1]d OR region->>'ru' ILIKE $%[1]d OR region->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.Active != nil {
args = append(args, *filter.Active)
conditions = append(conditions, fmt.Sprintf("active = $%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) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
row := r.client.QueryRow(ctx, `SELECT `+provinceSelectColumns+` FROM provinces WHERE id = $1`, id)
item, err := scanProvince(row)
if errors.Is(err, pgx.ErrNoRows) {
return province.ProvinceDTO{}, err
}
return item, err
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) {
@@ -87,14 +120,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM provinces WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
return r.generic.Delete(ctx, id)
}
func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, error) {
@@ -109,11 +135,7 @@ func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, e
return nameJSON, regionJSON, nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanProvince(row scannable) (province.ProvinceDTO, error) {
func scanProvince(row genericrepo.Scanner) (province.ProvinceDTO, error) {
var item province.ProvinceDTO
var nameJSON, regionJSON []byte
if err := row.Scan(&item.Id, &nameJSON, &regionJSON, &item.Active); err != nil {

View File

@@ -24,3 +24,16 @@ type UpdateProvinceDTO struct {
Region LocalizedName `json:"region" binding:"required"`
Active bool `json:"active"`
}
type ListFilter struct {
Name string
Region string
Active *bool
Page int
Limit int
}
type ListProvinceDTO struct {
Count int64 `json:"count"`
Provinces []ProvinceDTO `json:"provinces"`
}

View File

@@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
@@ -35,23 +36,34 @@ func (h *handler) Register(router *gin.RouterGroup) {
// list godoc
// @Summary List provinces
// @Description Returns all provinces
// @Description Returns paginated provinces with optional filters
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param name query string false "Filter by province name (en, ru, tm)"
// @Param region query string false "Filter by region (en, ru, tm)"
// @Param active query bool false "Filter by active status"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces [get]
func (h *handler) list(c *gin.Context) {
items, err := h.repository.List(c.Request.Context())
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list provinces failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(items))
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
@@ -195,3 +207,50 @@ func parseID(raw string) (int64, bool) {
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("name")); raw != "" {
filter.Name = raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
if raw := c.Query("active"); raw != "" {
active, err := strconv.ParseBool(raw)
if err != nil {
return ListFilter{}, false
}
filter.Active = &active
}
return filter, true
}

View File

@@ -3,7 +3,7 @@ package province
import "context"
type Repository interface {
List(ctx context.Context) ([]ProvinceDTO, error)
List(ctx context.Context, filter ListFilter) (ListProvinceDTO, error)
GetByID(ctx context.Context, id int64) (ProvinceDTO, error)
Create(ctx context.Context, dto CreateProvinceDTO) (ProvinceDTO, error)
Update(ctx context.Context, id int64, dto UpdateProvinceDTO) (ProvinceDTO, error)

30
internal/org/router.go Normal file
View File

@@ -0,0 +1,30 @@
// Package org groups the organizational/geographic hierarchy (provinces and
// branches) under one bounded context, replacing the flat internal/admin/*
// listing.
package org
import (
"online-back/internal/handlers"
"online-back/internal/org/branches"
branchesdb "online-back/internal/org/branches/db"
"online-back/internal/org/province"
provincedb "online-back/internal/org/province/db"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// Register wires every org module's handler onto router.
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
for _, h := range Handlers(client, logger) {
h.Register(router)
}
}
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
province.NewHandler(logger, provincedb.NewRepository(client, logger)),
branches.NewHandler(logger, branchesdb.NewRepository(client, logger)),
}
}

BIN
kickbacks.vsix Normal file

Binary file not shown.

View File

@@ -1,33 +0,0 @@
time="2026-07-06T12:22:36+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:22:36+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:54"
time="2026-07-06T12:22:36+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:56"
time="2026-07-06T12:23:43+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:23:43+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:54"
time="2026-07-06T12:31:34+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:31:34+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:45"
time="2026-07-06T12:41:53+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:41:53+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:45"
time="2026-07-06T12:51:53+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:51:53+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61"
time="2026-07-06T12:59:05+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T12:59:05+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61"
time="2026-07-06T14:03:17+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:03:17+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61"
time="2026-07-06T14:07:23+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:07:23+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T14:36:02+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:36:03+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T14:36:03+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:61"
time="2026-07-06T14:36:16+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:36:16+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T14:38:41+05:00" level=error msg="create branch failed: ERROR: missing FROM-clause entry for table \"b\" (SQLSTATE 42P01)" func="online-back/internal/admin/branches.(*handler).create()" file="handler.go:129"
time="2026-07-06T14:40:42+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:40:42+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T14:43:25+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:43:25+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T14:56:42+05:00" level=error msg="create loan type failed: ERROR: missing FROM-clause entry for table \"lt\" (SQLSTATE 42P01)" func="online-back/internal/admin/loantype.(*handler).create()" file="handler.go:121"
time="2026-07-06T14:58:32+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T14:58:32+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T15:53:35+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41"
time="2026-07-06T15:53:35+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59"
time="2026-07-06T15:53:35+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:61"

View File

@@ -0,0 +1,97 @@
// Package genericrepo factors out the List/GetByID/Delete/pagination
// pattern that was previously copy-pasted across every CRUD module's
// db/postgresql.go. Create and Update stay hand-written per module since
// their column lists and DTO mapping genuinely differ per entity.
package genericrepo
import (
"context"
"errors"
"fmt"
"online-back/pkg/client/postgresql"
"github.com/jackc/pgx/v4"
)
// Scanner is satisfied by both pgx.Row and pgx.Rows.
type Scanner interface {
Scan(dest ...interface{}) error
}
type Repository[T any] struct {
client postgresql.Client
table string
columns string
scan func(Scanner) (T, error)
}
func New[T any](client postgresql.Client, table, columns string, scan func(Scanner) (T, error)) *Repository[T] {
return &Repository[T]{client: client, table: table, columns: columns, scan: scan}
}
func (r *Repository[T]) GetByID(ctx context.Context, id int64) (T, error) {
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1`, id)
item, err := r.scan(row)
if errors.Is(err, pgx.ErrNoRows) {
var zero T
return zero, err
}
return item, err
}
func (r *Repository[T]) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM `+r.table+` WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
// List runs a paginated query. where must be empty or start with " WHERE "
// (see province's buildListQuery for the convention); args are the
// positional parameters referenced by where, in order. orderBy is the raw
// ORDER BY clause body (e.g. "id" or "id DESC"); pass "" to default to "id".
func (r *Repository[T]) List(ctx context.Context, where string, args []interface{}, page, limit int, orderBy string) ([]T, int64, error) {
if orderBy == "" {
orderBy = "id"
}
var count int64
countQuery := `SELECT COUNT(*) FROM ` + r.table + where
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return nil, 0, err
}
offset := (page - 1) * limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM %s%s ORDER BY %s LIMIT $%d OFFSET $%d`,
r.columns, r.table, where, orderBy, limitPlaceholder, offsetPlaceholder,
)
listArgs := append(append([]interface{}{}, args...), limit, offset)
rows, err := r.client.Query(ctx, listQuery, listArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var items []T
for rows.Next() {
item, err := r.scan(rows)
if err != nil {
return nil, 0, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, 0, err
}
return items, count, nil
}