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,153 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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
|
||||
generic *genericrepo.Repository[paymentcard.PaymentCardDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository {
|
||||
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`
|
||||
|
||||
const cardReturningColumns = `id, price, name, notes, active`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return paymentcard.ListPaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.CardName != "" {
|
||||
args = append(args, likePattern(filter.CardName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
c.name->>'en' ILIKE $%[1]d OR c.name->>'ru' ILIKE $%[1]d OR c.name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Active != nil {
|
||||
args = append(args, *filter.Active)
|
||||
conditions = append(conditions, fmt.Sprintf("c.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) (paymentcard.PaymentCardDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
||||
name, err := marshalName(dto.Title)
|
||||
if err != nil {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO card_types (price, name, notes, active)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.UpdatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
||||
name, err := marshalName(dto.Title)
|
||||
if err != nil {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET
|
||||
price = $1, name = $2, notes = $3, active = $4
|
||||
WHERE id = $5
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET active = $1
|
||||
WHERE id = $2
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
|
||||
return json.Marshal(title)
|
||||
}
|
||||
|
||||
func scanPaymentCard(row genericrepo.Scanner) (paymentcard.PaymentCardDTO, error) {
|
||||
var item paymentcard.PaymentCardDTO
|
||||
var nameJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Price, &nameJSON, &item.Notes, &item.Active,
|
||||
); err != nil {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Title); err != nil {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package paymentcard
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type PaymentCardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Price string `json:"price"`
|
||||
Title LocalizedText `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreatePaymentCardDTO struct {
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardDTO struct {
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardActiveDTO struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
CardName string
|
||||
Active *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListPaymentCardDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
PaymentCards []PaymentCardDTO `json:"paymentCards"`
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package paymentcard
|
||||
|
||||
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 = "/payment-cards"
|
||||
|
||||
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.PUT("/:id/active", h.updateActive)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List payment cards
|
||||
// @Description Returns paginated payment cards with optional filters
|
||||
// @Tags payment-card
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param card_name query string false "Filter by card title (en, ru, tm)"
|
||||
// @Param active query bool false "Filter by active"
|
||||
// @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 /payment-cards [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 payment cards failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get payment card by ID
|
||||
// @Description Returns a single payment card
|
||||
// @Tags payment-card
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Payment card ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{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 payment card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create payment card
|
||||
// @Description Creates a new payment card
|
||||
// @Tags payment-card
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePaymentCardDTO true "Payment card payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePaymentCardDTO
|
||||
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 payment card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update payment card
|
||||
// @Description Updates an existing payment card
|
||||
// @Tags payment-card
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Payment card ID"
|
||||
// @Param body body UpdatePaymentCardDTO true "Payment card payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{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 UpdatePaymentCardDTO
|
||||
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 payment card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// updateActive godoc
|
||||
// @Summary Update payment card active
|
||||
// @Description Enables or disables a payment card
|
||||
// @Tags payment-card
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Payment card ID"
|
||||
// @Param body body UpdatePaymentCardActiveDTO true "Active payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id}/active [put]
|
||||
func (h *handler) updateActive(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdatePaymentCardActiveDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.UpdateActive(c.Request.Context(), id, dto.Active)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update payment card active failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete payment card
|
||||
// @Description Deletes a payment card
|
||||
// @Tags payment-card
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Payment card ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{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 payment card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card 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("card_name")); raw != "" {
|
||||
filter.CardName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Active = &active
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package paymentcard
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPaymentCardDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (PaymentCardDTO, error)
|
||||
Create(ctx context.Context, dto CreatePaymentCardDTO) (PaymentCardDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePaymentCardDTO) (PaymentCardDTO, error)
|
||||
UpdateActive(ctx context.Context, id int64, active bool) (PaymentCardDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in new issue
Block a user