add cards folder

This commit is contained in:
2026-07-13 18:47:35 +05:00
parent 6705c4ce91
commit 7e3a5cebcc
19 changed files with 4079 additions and 0 deletions

View File

@@ -0,0 +1,228 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/admin/cardorder"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.Repository {
return &repository{client: client, 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)
var count int64
countQuery := `SELECT COUNT(*) FROM card_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM card_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
defer rows.Close()
var items []cardorder.CardOrderDTO
for rows.Next() {
item, err := scanCardOrder(rows)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
}
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) {
query := fmt.Sprintf(`SELECT %s FROM card_orders WHERE id = $1`, cardOrderColumnsSQL)
item, err := scanCardOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return cardorder.CardOrderDTO{}, err
}
return item, nil
}
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 {
tag, err := r.client.Exec(ctx, `DELETE FROM card_orders WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCardOrder(row scannable) (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,204 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/admin/cardpinorders"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository {
return &repository{client: client, 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)
var count int64
countQuery := `SELECT COUNT(*) FROM card_pin_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM card_pin_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardPinOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
defer rows.Close()
var items []cardpinorders.CardPinOrderDTO
for rows.Next() {
item, err := scanCardPinOrder(rows)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
}
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) {
query := fmt.Sprintf(`SELECT %s FROM card_pin_orders WHERE id = $1`, cardPinOrderColumnsSQL)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}
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 {
tag, err := r.client.Exec(ctx, `DELETE FROM card_pin_orders WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCardPinOrder(row scannable) (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,177 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/admin/cards"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cards.Repository {
return &repository{client: client, 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)
var count int64
countQuery := `SELECT COUNT(*) FROM cards` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cards.ListCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM cards%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return cards.ListCardDTO{}, err
}
defer rows.Close()
var items []cards.CardDTO
for rows.Next() {
item, err := scanCard(rows)
if err != nil {
return cards.ListCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cards.ListCardDTO{}, err
}
return cards.ListCardDTO{Count: count, Cards: items}, nil
}
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) {
query := fmt.Sprintf(`SELECT %s FROM cards WHERE id = $1`, cardColumnsSQL)
item, err := scanCard(r.client.QueryRow(ctx, query, id))
if err != nil {
return cards.CardDTO{}, err
}
return item, nil
}
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 {
tag, err := r.client.Exec(ctx, `DELETE FROM cards WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanCard(row scannable) (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
}