Files
online-backend/internal/org/province/handler.go
GuwandykA 1987d4f596 Add region and etrap APIs for branch create form.
Expose distinct regions and etraps-by-region under provinces and branches, and seed real etraps per welayat.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 12:12:07 +05:00

334 lines
9.3 KiB
Go

package province
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 = "/provinces"
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("/regions", h.listRegions)
group.GET("/etraps", h.listEtraps)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List provinces
// @Description Returns paginated provinces with optional filters
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param name query string false "Filter by province name (en, ru, tm)"
// @Param region query string false "Filter by region (en, ru, tm)"
// @Param active query bool false "Filter by active status"
// @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 /provinces [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 provinces failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listRegions godoc
// @Summary List distinct regions
// @Description Returns unique regions from the provinces table (for region dropdown)
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param active query bool false "Only active provinces" default(true)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/regions [get]
func (h *handler) listRegions(c *gin.Context) {
activeOnly, ok := parseActiveOnly(c, true)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.ListRegions(c.Request.Context(), activeOnly)
if err != nil {
h.logger.Errorf("list regions failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listEtraps godoc
// @Summary List etraps by region
// @Description Returns provinces (etraps) belonging to the selected region
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param region query string true "Region name (en, ru or tm)"
// @Param active query bool false "Only active etraps" default(true)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/etraps [get]
func (h *handler) listEtraps(c *gin.Context) {
region := strings.TrimSpace(c.Query("region"))
if region == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
activeOnly, ok := parseActiveOnly(c, true)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.ListEtrapsByRegion(c.Request.Context(), region, activeOnly)
if err != nil {
h.logger.Errorf("list etraps by region failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get province by ID
// @Description Returns a single province
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create province
// @Description Creates a new province
// @Tags province
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateProvinceDTO true "Province payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces [post]
func (h *handler) create(c *gin.Context) {
var dto CreateProvinceDTO
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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update province
// @Description Updates an existing province
// @Tags province
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Param body body UpdateProvinceDTO true "Province payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 UpdateProvinceDTO
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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete province
// @Description Deletes a province
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("province 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
}
func parseActiveOnly(c *gin.Context, defaultValue bool) (bool, bool) {
raw := c.Query("active")
if raw == "" {
return defaultValue, true
}
active, err := strconv.ParseBool(raw)
if err != nil {
return false, false
}
return active, 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("name")); raw != "" {
filter.Name = raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
if raw := c.Query("active"); raw != "" {
active, err := strconv.ParseBool(raw)
if err != nil {
return ListFilter{}, false
}
filter.Active = &active
}
return filter, true
}