add cards folder
This commit is contained in:
177
internal/admin/cards/db/postgresql.go
Normal file
177
internal/admin/cards/db/postgresql.go
Normal 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
|
||||
}
|
||||
45
internal/admin/cards/dto.go
Normal file
45
internal/admin/cards/dto.go
Normal 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"`
|
||||
}
|
||||
251
internal/admin/cards/handler.go
Normal file
251
internal/admin/cards/handler.go
Normal 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
|
||||
}
|
||||
11
internal/admin/cards/storage.go
Normal file
11
internal/admin/cards/storage.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user