Files
online-backend/internal/currency/handler.go
GuwandykA f1337706f0
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
swagger: document the ?lang= query parameter on every admin endpoint
appresult.Localize applies to all /api/admin routes, so each handler's
godoc now declares lang (tm, ru, en, all; default tm) and Swagger UI
offers it as a dropdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:08:32 +05:00

285 lines
8.5 KiB
Go

package currency
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/currencies"
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 := rbac.Group(router, baseURL, rbac.Catalog(perm.Currencies))
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 currency rates
// @Description Returns paginated currency exchange rates
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by currency code"
// @Param currency_from query string false "Filter by source currency"
// @Param currency_to query string false "Filter by target currency"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} ListCurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [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 currencies failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get currency rate by ID
// @Description Returns a single currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.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 currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create currency rate
// @Description Creates a new currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCurrencyDTO true "Currency rate payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.CreatedBy = currentUserID(c)
item, err := h.repository.Create(c.Request.Context(), dto)
if errors.Is(err, ErrDuplicate) {
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
return
}
if err != nil {
h.logger.Errorf("create currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update currency rate
// @Description Updates an existing currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param body body UpdateCurrencyDTO true "Currency rate payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.UpdatedBy = currentUserID(c)
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if errors.Is(err, ErrDuplicate) {
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
return
}
if err != nil {
h.logger.Errorf("update currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete currency rate
// @Description Deletes a currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.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 currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("currency removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{Page: shared.DefaultPage, Limit: shared.DefaultLimit}
if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > shared.MaxLimit {
limit = shared.MaxLimit
}
filter.Limit = limit
}
filter.Search = queryValue(c, "search", "q")
filter.CurrencyFrom = strings.ToUpper(queryValue(c, "currency_from", "currencyFrom"))
filter.CurrencyTo = strings.ToUpper(queryValue(c, "currency_to", "currencyTo"))
return filter, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func currentUserID(c *gin.Context) *int64 {
rawID, exists := c.Get("id")
if !exists {
return nil
}
switch id := rawID.(type) {
case int64:
if id > 0 {
return &id
}
case int:
if id > 0 {
v := int64(id)
return &v
}
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
if err == nil && parsed > 0 {
return &parsed
}
}
return nil
}