Files
online-backend/internal/org/branches/handler.go
GuwandykA d1a6fcaadc
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
ch some
2026-09-04 19:33:26 +05:00

368 lines
10 KiB
Go

package branches
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/org/province"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/branches"
type handler struct {
logger *logging.Logger
repository Repository
provinces province.Repository
}
func NewHandler(logger *logging.Logger, repository Repository, provinces province.Repository) handlers.Handler {
return &handler{logger: logger, repository: repository, provinces: provinces}
}
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 branches
// @Description Returns paginated branches with optional filters
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param province_id query int false "Filter by province ID"
// @Param province_name query string false "Filter by province name (en, ru, tm)"
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
// @Param unique_code query string false "Filter by unique code"
// @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 /branches [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 branches failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.IsAdminGuard(c) {
for i := range result.Branches {
clearBranchSecrets(&result.Branches[i])
}
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listRegions godoc
// @Summary List regions for branch create
// @Description Returns distinct regions from provinces (use before selecting etrap/provinceId)
// @Tags branches
// @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 /branches/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.provinces.ListRegions(c.Request.Context(), activeOnly)
if err != nil {
h.logger.Errorf("list branch 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 for branch create
// @Description Returns provinces (etraps) for the selected region; pick id as provinceId
// @Tags branches
// @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 /branches/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.provinces.ListEtrapsByRegion(c.Request.Context(), region, activeOnly)
if err != nil {
h.logger.Errorf("list branch etraps failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get branch by ID
// @Description Returns a single branch
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.Id) {
return
}
if !rbac.IsAdminGuard(c) {
clearBranchSecrets(&item)
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create branch
// @Description Creates a new branch
// @Tags branches
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateBranchDTO true "Branch payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches [post]
func (h *handler) create(c *gin.Context) {
var dto CreateBranchDTO
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 {
if isClientError(err) {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
h.logger.Errorf("create branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update branch
// @Description Updates an existing branch
// @Tags branches
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Param body body UpdateBranchDTO true "Branch payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 UpdateBranchDTO
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 {
if isClientError(err) {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
h.logger.Errorf("update branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete branch
// @Description Deletes a branch
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("branch removed"))
}
func isClientError(err error) bool {
msg := err.Error()
return msg == "province not found" || msg == "unique code already exists"
}
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
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("province_id"); raw != "" {
id, ok := shared.ParseID(raw)
if !ok {
return ListFilter{}, false
}
filter.ProvinceID = &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 > shared.MaxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("province_name")); raw != "" {
filter.ProvinceName = raw
}
if raw := strings.TrimSpace(c.Query("branch_name")); raw != "" {
filter.BranchName = raw
}
if raw := strings.TrimSpace(c.Query("unique_code")); raw != "" {
filter.UniqueCode = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func clearBranchSecrets(item *BranchDTO) {
if item == nil {
return
}
item.BillingUsername = ""
item.BillingPassword = ""
item.BillingSberUsername = ""
item.BillingSberPassword = ""
item.BillingVisaMasterUsername = ""
item.BillingVisaMasterPassword = ""
item.BillingSwiftUsername = ""
item.BillingSwiftPassword = ""
}