changed arhitecture

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

View File

@@ -0,0 +1,189 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cardorder"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
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,
generic: genericrepo.New(client, "card_orders", cardOrderColumnsSQL, scanCardOrder),
logger: logger,
}
}
// cardOrderWritableColumns lists every card_orders column except id, created_at and
// updated_at, in the exact order CreateCardOrderDTO/UpdateCardOrderDTO fields are read.
var cardOrderWritableColumns = []string{
"unique_id", "card_state_id", "card_type_id", "region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "old_surname", "citizenship",
"passport_serie", "passport_id", "passport_given_at", "passport_given_by", "born_place",
"job_location", "passport_address", "real_address", "phone", "phone_additional",
"status", "passport_one", "passport_two", "passport_three", "passport_four", "notes", "user_id", "paid",
}
var cardOrderColumns = append(append([]string{"id"}, cardOrderWritableColumns...), "created_at", "updated_at")
var cardOrderColumnsSQL = strings.Join(cardOrderColumns, ", ")
var cardOrderWritableColumnsSQL = strings.Join(cardOrderWritableColumns, ", ")
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
pending := "pending"
return &pending
}
return status
}
func resolvePaid(paid *bool) bool {
if paid == nil {
return false
}
return *paid
}
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, resolvePaid(dto.Paid),
}
}
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, dto.Paid,
}
}
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
}
func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
}
if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
}
if filter.CardStateId != nil {
args = append(args, *filter.CardStateId)
conditions = append(conditions, fmt.Sprintf("card_state_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
args := createArgs(dto)
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_orders (%s) VALUES (%s) RETURNING %s`,
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardOrderColumnsSQL,
)
return scanCardOrder(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardOrderWritableColumns))
for i, column := range cardOrderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL,
)
item, err := scanCardOrder(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardorder.CardOrderDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
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,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.OldSurname, &item.Citizenship,
&item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy, &item.BornPlace,
&item.JobLocation, &item.PassportAddress, &item.RealAddress, &item.Phone, &item.PhoneAdditional,
&item.Status, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour, &item.Notes, &item.UserId, &item.Paid,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
return cardorder.CardOrderDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,118 @@
package cardorder
import "time"
type CardOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId"`
CardTypeId int64 `json:"cardTypeId"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportGivenAt time.Time `json:"passportGivenAt"`
PassportGivenBy string `json:"passportGivenBy"`
BornPlace string `json:"bornPlace"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId" binding:"required"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid *bool `json:"paid"`
}
type UpdateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId" binding:"required"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid bool `json:"paid"`
}
type ListFilter struct {
Status *string
BranchId *int64
UserId *int64
CardStateId *int64
CardTypeId *int64
Region string
Page int
Limit int
}
type ListCardOrderDTO struct {
Count int64 `json:"count"`
CardOrders []CardOrderDTO `json:"cardOrders"`
}

View File

@@ -0,0 +1,283 @@
package cardorder
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 = "/card-orders"
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 card orders
// @Description Returns paginated card orders with optional filters
// @Tags card-orders
// @Produce json
// @Security BearerAuth
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by user ID"
// @Param card_state_id query int false "Filter by card state ID"
// @Param card_type_id query int false "Filter by card type ID"
// @Param region query string false "Filter by region"
// @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 /card-orders [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 card orders failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card order by ID
// @Description Returns a single card order
// @Tags card-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{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 card order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card order
// @Description Creates a new card order
// @Tags card-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardOrderDTO true "Card order payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardOrderDTO
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 card order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card order
// @Description Updates an existing card order
// @Tags card-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Param body body UpdateCardOrderDTO true "Card order payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{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 UpdateCardOrderDTO
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 card order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card order
// @Description Deletes a card order
// @Tags card-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{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 card order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card order 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("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
if raw := c.Query("card_state_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardStateId = &id
}
if raw := c.Query("card_type_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardTypeId = &id
}
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("status")); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package cardorder
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardOrderDTO, error)
GetByID(ctx context.Context, id int64) (CardOrderDTO, error)
Create(ctx context.Context, dto CreateCardOrderDTO) (CardOrderDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardOrderDTO) (CardOrderDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,165 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cardpinorders"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
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,
generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder),
logger: logger,
}
}
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
var cardPinOrderWritableColumns = []string{
"unique_id", "user_id", "card_type_id", "card_number", "region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
"status", "notes",
}
var cardPinOrderColumns = append(append([]string{"id"}, cardPinOrderWritableColumns...), "created_at", "updated_at")
var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
}
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
}
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
}
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
}
if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
args := createArgs(dto)
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_pin_orders (%s) VALUES (%s) RETURNING %s`,
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
)
return scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardPinOrderWritableColumns))
for i, column := range cardPinOrderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
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,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
&item.Status, &item.Notes,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,87 @@
package cardpinorders
import "time"
type CardPinOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Status *string `json:"status"`
Notes *string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type UpdateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type ListFilter struct {
Status *string
BranchId *int64
UserId *int64
CardTypeId *int64
Region string
Page int
Limit int
}
type ListCardPinOrderDTO struct {
Count int64 `json:"count"`
CardPinOrders []CardPinOrderDTO `json:"cardPinOrders"`
}

View File

@@ -0,0 +1,274 @@
package cardpinorders
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 = "/card-pin-orders"
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 card pin orders
// @Description Returns paginated card pin orders with optional filters
// @Tags card-pin-orders
// @Produce json
// @Security BearerAuth
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by user ID"
// @Param card_type_id query int false "Filter by card type ID"
// @Param region query string false "Filter by region"
// @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 /card-pin-orders [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 card pin orders failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card pin order by ID
// @Description Returns a single card pin order
// @Tags card-pin-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{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 card pin order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card pin order
// @Description Creates a new card pin order
// @Tags card-pin-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardPinOrderDTO true "Card pin order payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardPinOrderDTO
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 card pin order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card pin order
// @Description Updates an existing card pin order
// @Tags card-pin-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Param body body UpdateCardPinOrderDTO true "Card pin order payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{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 UpdateCardPinOrderDTO
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 card pin order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card pin order
// @Description Deletes a card pin order
// @Tags card-pin-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{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 card pin order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin order 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("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
if raw := c.Query("card_type_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardTypeId = &id
}
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("status")); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package cardpinorders
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardPinOrderDTO, error)
GetByID(ctx context.Context, id int64) (CardPinOrderDTO, error)
Create(ctx context.Context, dto CreateCardPinOrderDTO) (CardPinOrderDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardPinOrderDTO) (CardPinOrderDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,138 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cards"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
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,
generic: genericrepo.New(client, "cards", cardColumnsSQL, scanCard),
logger: logger,
}
}
// cardWritableColumns lists every cards column except id, created_at and
// updated_at, in the exact order CreateCardDTO/UpdateCardDTO fields are read.
var cardWritableColumns = []string{
"user_id", "number", "name", "month", "year", "type",
}
var cardColumns = append(append([]string{"id"}, cardWritableColumns...), "created_at", "updated_at")
var cardColumnsSQL = strings.Join(cardColumns, ", ")
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
func createArgs(dto cards.CreateCardDTO) []interface{} {
return []interface{}{
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
}
}
func updateArgs(dto cards.UpdateCardDTO) []interface{} {
return []interface{}{
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
}
}
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return cards.ListCardDTO{}, err
}
return cards.ListCardDTO{Count: count, Cards: items}, nil
}
func buildListQuery(filter cards.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
}
if filter.Type != nil {
args = append(args, *filter.Type)
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
args := createArgs(dto)
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO cards (%s) VALUES (%s) RETURNING %s`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "), cardColumnsSQL,
)
return scanCard(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardWritableColumns))
for i, column := range cardWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL,
)
item, err := scanCard(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cards.CardDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
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,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
return cards.CardDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,45 @@
package cards
import "time"
type CardDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"userId"`
Number string `json:"number"`
Name string `json:"name"`
Month string `json:"month"`
Year *string `json:"year"`
Type *string `json:"type"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardDTO struct {
UserId *int64 `json:"userId"`
Number string `json:"number" binding:"required"`
Name string `json:"name" binding:"required"`
Month string `json:"month" binding:"required"`
Year *string `json:"year"`
Type *string `json:"type"`
}
type UpdateCardDTO struct {
UserId *int64 `json:"userId"`
Number string `json:"number" binding:"required"`
Name string `json:"name" binding:"required"`
Month string `json:"month" binding:"required"`
Year *string `json:"year"`
Type *string `json:"type"`
}
type ListFilter struct {
UserId *int64
Type *string
Page int
Limit int
}
type ListCardDTO struct {
Count int64 `json:"count"`
Cards []CardDTO `json:"cards"`
}

View File

@@ -0,0 +1,251 @@
package cards
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 = "/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.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List cards
// @Description Returns paginated cards with optional filters
// @Tags cards
// @Produce json
// @Security BearerAuth
// @Param user_id query int false "Filter by user ID"
// @Param type query string false "Filter by card type"
// @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 /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 cards failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card by ID
// @Description Returns a single card
// @Tags cards
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /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 card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card
// @Description Creates a new card
// @Tags cards
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardDTO true "Card payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /cards [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardDTO
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 card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card
// @Description Updates an existing card
// @Tags cards
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Param body body UpdateCardDTO true "Card payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /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 UpdateCardDTO
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 card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card
// @Description Deletes a card
// @Tags cards
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /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 card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("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("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
if raw := strings.TrimSpace(c.Query("type")); raw != "" {
filter.Type = &raw
}
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
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package cards
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardDTO, error)
GetByID(ctx context.Context, id int64) (CardDTO, error)
Create(ctx context.Context, dto CreateCardDTO) (CardDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardDTO) (CardDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

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

View File

@@ -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"`
}

View File

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

View File

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

View File

@@ -0,0 +1,135 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"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
generic *genericrepo.Repository[reasonscard.ReasonCardDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository {
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`
const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
}
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.ReasonName != "" {
args = append(args, likePattern(filter.ReasonName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
r.name->>'en' ILIKE $%[1]d OR r.name->>'ru' ILIKE $%[1]d OR r.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) (reasonscard.ReasonCardDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
name, err := marshalName(dto.Title)
if err != nil {
return reasonscard.ReasonCardDTO{}, err
}
active := true
if dto.Active != nil {
active = *dto.Active
}
query := fmt.Sprintf(`
INSERT INTO card_states (price, name, notes, active)
VALUES ($1, $2, $3, $4)
RETURNING %s`, reasonReturningColumns)
return scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, active))
}
func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.UpdateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
name, err := marshalName(dto.Title)
if err != nil {
return reasonscard.ReasonCardDTO{}, err
}
query := fmt.Sprintf(`
UPDATE card_states SET
price = $1, name = $2, notes = $3, active = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5
RETURNING %s`, reasonReturningColumns)
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
if errors.Is(err, pgx.ErrNoRows) {
return reasonscard.ReasonCardDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}
func scanReasonCard(row genericrepo.Scanner) (reasonscard.ReasonCardDTO, error) {
var item reasonscard.ReasonCardDTO
var nameJSON []byte
if err := row.Scan(
&item.Id, &item.Price, &nameJSON, &item.Notes, &item.Active, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return reasonscard.ReasonCardDTO{}, err
}
if err := json.Unmarshal(nameJSON, &item.Title); err != nil {
return reasonscard.ReasonCardDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,44 @@
package reasonscard
import "time"
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type ReasonCardDTO struct {
Id int64 `json:"id"`
Title LocalizedText `json:"title"`
Price string `json:"price"`
Notes string `json:"notes"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
}
type UpdateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type ListFilter struct {
ReasonName string
Page int
Limit int
}
type ListReasonCardDTO struct {
Count int64 `json:"count"`
ReasonCards []ReasonCardDTO `json:"reasonCards"`
}

View File

@@ -0,0 +1,242 @@
package reasonscard
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 = "/reasons-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.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List reason cards
// @Description Returns paginated reason cards with optional filters
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param reason_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 /reasons-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 reason cards failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get reason card by ID
// @Description Returns a single reason card
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create reason card
// @Description Creates a new reason card
// @Tags reason-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateReasonCardDTO true "Reason card payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards [post]
func (h *handler) create(c *gin.Context) {
var dto CreateReasonCardDTO
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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update reason card
// @Description Updates an existing reason card
// @Tags reason-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Param body body UpdateReasonCardDTO true "Reason card payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-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 UpdateReasonCardDTO
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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete reason card
// @Description Deletes a reason card
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("reason 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("reason_name")); raw != "" {
filter.ReasonName = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package reasonscard
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListReasonCardDTO, error)
GetByID(ctx context.Context, id int64) (ReasonCardDTO, error)
Create(ctx context.Context, dto CreateReasonCardDTO) (ReasonCardDTO, error)
Update(ctx context.Context, id int64, dto UpdateReasonCardDTO) (ReasonCardDTO, error)
Delete(ctx context.Context, id int64) error
}

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