changed arhitecture
This commit is contained in:
1 parent
7e3a5cebcc
commit
585ba63bc2
95 files changed
+4985
-1360
No files matched your search
@@ -0,0 +1,146 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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
|
||||
generic *genericrepo.Repository[loantype.LoanTypeDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Repository {
|
||||
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`
|
||||
|
||||
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) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.LoanTypeName != "" {
|
||||
args = append(args, likePattern(filter.LoanTypeName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
lt.name->>'en' ILIKE $%[1]d OR lt.name->>'ru' ILIKE $%[1]d OR lt.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) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
|
||||
name, notes, err := marshalJSON(dto.Title, dto.Content)
|
||||
if err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loan_types (name, tax, maturity, notes, active)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
return scanLoanType(r.client.QueryRow(ctx, query, name, dto.Tax, dto.LoanTerm, notes, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
|
||||
name, notes, err := marshalJSON(dto.Title, dto.Content)
|
||||
if err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_types SET
|
||||
name = $1, tax = $2, maturity = $3, notes = $4, active = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
item, err := scanLoanType(r.client.QueryRow(ctx, query, name, dto.Tax, dto.LoanTerm, notes, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) {
|
||||
titleJSON, err := json.Marshal(title)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
contentJSON, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return titleJSON, contentJSON, nil
|
||||
}
|
||||
|
||||
func scanLoanType(row genericrepo.Scanner) (loantype.LoanTypeDTO, error) {
|
||||
var item loantype.LoanTypeDTO
|
||||
var nameJSON, notesJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &nameJSON, &item.Tax, &item.LoanTerm, ¬esJSON, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Title); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(notesJSON, &item.Content); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package loantype
|
||||
|
||||
import "time"
|
||||
|
||||
type LocalizedTitle struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type LoanTypeDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Tax float64 `json:"tax"`
|
||||
LoanTerm string `json:"loanTerm"`
|
||||
Content LocalizedTitle `json:"content"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanTypeDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Tax float64 `json:"tax" binding:"required"`
|
||||
LoanTerm string `json:"loanTerm" binding:"required"`
|
||||
Content LocalizedTitle `json:"content" binding:"required"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanTypeDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Tax float64 `json:"tax" binding:"required"`
|
||||
LoanTerm string `json:"loanTerm" binding:"required"`
|
||||
Content LocalizedTitle `json:"content" binding:"required"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
LoanTypeName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanTypeDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanTypes []LoanTypeDTO `json:"loanTypes"`
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package loantype
|
||||
|
||||
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 = "/loan-types"
|
||||
|
||||
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 loan types
|
||||
// @Description Returns paginated loan types with optional filters
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param loan_type_name query string false "Filter by title (en, ru, tm)"
|
||||
// @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 /loan-types [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 loan types failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan type by ID
|
||||
// @Description Returns a single loan type
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan type
|
||||
// @Description Creates a new loan type
|
||||
// @Tags loan-type
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanTypeDTO true "Loan type payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanTypeDTO
|
||||
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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan type
|
||||
// @Description Updates an existing loan type
|
||||
// @Tags loan-type
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Param body body UpdateLoanTypeDTO true "Loan type payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 UpdateLoanTypeDTO
|
||||
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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan type
|
||||
// @Description Deletes a loan type
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan type 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("loan_type_name")); raw != "" {
|
||||
filter.LoanTypeName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package loantype
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanTypeDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanTypeDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanTypeDTO) (LoanTypeDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanTypeDTO) (LoanTypeDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in new issue
Block a user