diff --git a/db/seed.sql b/db/seed.sql index 2db3528..048029b 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -122,38 +122,84 @@ WHERE p.code IN ( ); -- --------------------------------------------------------------------------- --- Provinces (Turkmenistan) +-- Provinces (Turkmenistan) — name = etrap, region = welaýat -- --------------------------------------------------------------------------- INSERT INTO provinces (name, region, active) VALUES +-- Paýtagt ( '{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, '{"en":"Capital","ru":"Столица","tm":"Paýtagt"}'::json, true ), +-- Ahal welaýaty ( - '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, + '{"en":"Anew","ru":"Анев","tm":"Änew"}'::json, '{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, true ), ( - '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, + '{"en":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json, + '{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, + true +), +( + '{"en":"Tejen","ru":"Теджен","tm":"Tejen"}'::json, + '{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, + true +), +-- Balkan welaýaty +( + '{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json, '{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, true ), +( + '{"en":"Turkmenbashy","ru":"Туркменбаши","tm":"Türkmenbaşy"}'::json, + '{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, + true +), +( + '{"en":"Serdar","ru":"Сердар","tm":"Serdar"}'::json, + '{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, + true +), +-- Daşoguz welaýaty ( '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, '{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json, true ), ( - '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, + '{"en":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json, + '{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json, + true +), +-- Lebap welaýaty +( + '{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json, '{"en":"Lebap Region","ru":"Лебапский велаят","tm":"Lebap welaýaty"}'::json, true ), +( + '{"en":"Farap","ru":"Фарап","tm":"Farap"}'::json, + '{"en":"Lebap Region","ru":"Лебапский велаят","tm":"Lebap welaýaty"}'::json, + true +), +-- Mary welaýaty ( '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, '{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json, true +), +( + '{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json, + '{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json, + true +), +( + '{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json, + '{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json, + true ); -- --------------------------------------------------------------------------- @@ -185,31 +231,31 @@ INSERT INTO branches ( 'BLK-01', '{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}'::json, '{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}'::json, - 'BL', 3, '+993 22 31 00 01', 'billing_blk', 'billing_pass', true + 'BL', 5, '+993 22 31 00 01', 'billing_blk', 'billing_pass', true ), ( 'DSZ-01', '{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}'::json, '{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}'::json, - 'DZ', 4, '+993 32 41 00 01', 'billing_dsz', 'billing_pass', true + 'DZ', 8, '+993 32 41 00 01', 'billing_dsz', 'billing_pass', true ), ( 'LBP-01', '{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}'::json, '{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}'::json, - 'LB', 5, '+993 42 51 00 01', 'billing_lbp', 'billing_pass', true + 'LB', 10, '+993 42 51 00 01', 'billing_lbp', 'billing_pass', true ), ( 'MRY-01', '{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}'::json, '{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}'::json, - 'MR', 6, '+993 52 61 00 01', 'billing_mry', 'billing_pass', true + 'MR', 12, '+993 52 61 00 01', 'billing_mry', 'billing_pass', true ), ( 'MRY-02', '{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}'::json, '{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}'::json, - 'MR', 6, '+993 52 62 00 01', 'billing_mry2', 'billing_pass', false + 'MR', 13, '+993 52 62 00 01', 'billing_mry2', 'billing_pass', false ); INSERT INTO branch_user (branch_id, user_id) VALUES @@ -455,7 +501,7 @@ INSERT INTO loan_orders ( 'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '404040', '2012-04-22', 'Mary Police', 'Mary', '1985-06-30', NULL, '+993 63 30 40 50', NULL, NULL, - 'MR', 6, 'Mary Textile', 'ACC-3003', + 'MR', 12, 'Mary Textile', 'ACC-3003', '2015-01-10', '5200', 'Engineer', 'higher', 'married', 'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg', @@ -472,7 +518,7 @@ INSERT INTO loan_orders ( 'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060', '2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12', 'ogul@mail.tm', '+993 64 40 50 60', NULL, NULL, - 'LB', 5, 'Self-employed', NULL, + 'LB', 10, 'Self-employed', NULL, '2021-03-01', '6000', 'Entrepreneur', 'secondary', 'single', 'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg', diff --git a/docs/docs.go b/docs/docs.go index f74b5d2..ad4e432 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -410,6 +410,105 @@ const docTemplate = `{ } } }, + "/branches/etraps": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns provinces (etraps) for the selected region; pick id as provinceId", + "produces": [ + "application/json" + ], + "tags": [ + "branches" + ], + "summary": "List etraps by region for branch create", + "parameters": [ + { + "type": "string", + "description": "Region name (en, ru or tm)", + "name": "region", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active etraps", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/branches/regions": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns distinct regions from provinces (use before selecting etrap/provinceId)", + "produces": [ + "application/json" + ], + "tags": [ + "branches" + ], + "summary": "List regions for branch create", + "parameters": [ + { + "type": "boolean", + "default": true, + "description": "Only active provinces", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/branches/{id}": { "get": { "security": [ @@ -4064,6 +4163,105 @@ const docTemplate = `{ } } }, + "/provinces/etraps": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns provinces (etraps) belonging to the selected region", + "produces": [ + "application/json" + ], + "tags": [ + "province" + ], + "summary": "List etraps by region", + "parameters": [ + { + "type": "string", + "description": "Region name (en, ru or tm)", + "name": "region", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active etraps", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/provinces/regions": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns unique regions from the provinces table (for region dropdown)", + "produces": [ + "application/json" + ], + "tags": [ + "province" + ], + "summary": "List distinct regions", + "parameters": [ + { + "type": "boolean", + "default": true, + "description": "Only active provinces", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/provinces/{id}": { "get": { "security": [ diff --git a/docs/swagger.json b/docs/swagger.json index 5975cec..81aba00 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -404,6 +404,105 @@ } } }, + "/branches/etraps": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns provinces (etraps) for the selected region; pick id as provinceId", + "produces": [ + "application/json" + ], + "tags": [ + "branches" + ], + "summary": "List etraps by region for branch create", + "parameters": [ + { + "type": "string", + "description": "Region name (en, ru or tm)", + "name": "region", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active etraps", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/branches/regions": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns distinct regions from provinces (use before selecting etrap/provinceId)", + "produces": [ + "application/json" + ], + "tags": [ + "branches" + ], + "summary": "List regions for branch create", + "parameters": [ + { + "type": "boolean", + "default": true, + "description": "Only active provinces", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/branches/{id}": { "get": { "security": [ @@ -4058,6 +4157,105 @@ } } }, + "/provinces/etraps": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns provinces (etraps) belonging to the selected region", + "produces": [ + "application/json" + ], + "tags": [ + "province" + ], + "summary": "List etraps by region", + "parameters": [ + { + "type": "string", + "description": "Region name (en, ru or tm)", + "name": "region", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active etraps", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/provinces/regions": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns unique regions from the provinces table (for region dropdown)", + "produces": [ + "application/json" + ], + "tags": [ + "province" + ], + "summary": "List distinct regions", + "parameters": [ + { + "type": "boolean", + "default": true, + "description": "Only active provinces", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/provinces/{id}": { "get": { "security": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 40cdfd0..8b3516f 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1579,6 +1579,70 @@ paths: summary: Update branch tags: - branches + /branches/etraps: + get: + description: Returns provinces (etraps) for the selected region; pick id as + provinceId + parameters: + - description: Region name (en, ru or tm) + in: query + name: region + required: true + type: string + - default: true + description: Only active etraps + in: query + name: active + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List etraps by region for branch create + tags: + - branches + /branches/regions: + get: + description: Returns distinct regions from provinces (use before selecting etrap/provinceId) + parameters: + - default: true + description: Only active provinces + in: query + name: active + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List regions for branch create + tags: + - branches /card-orders: get: description: Returns paginated card orders with optional filters @@ -3917,6 +3981,69 @@ paths: summary: Update province tags: - province + /provinces/etraps: + get: + description: Returns provinces (etraps) belonging to the selected region + parameters: + - description: Region name (en, ru or tm) + in: query + name: region + required: true + type: string + - default: true + description: Only active etraps + in: query + name: active + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List etraps by region + tags: + - province + /provinces/regions: + get: + description: Returns unique regions from the provinces table (for region dropdown) + parameters: + - default: true + description: Only active provinces + in: query + name: active + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List distinct regions + tags: + - province /reasons-cards: get: description: Returns paginated reason cards with optional filters diff --git a/internal/org/branches/handler.go b/internal/org/branches/handler.go index 3ca0453..1d32932 100644 --- a/internal/org/branches/handler.go +++ b/internal/org/branches/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/org/province" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -19,15 +20,18 @@ const baseURL = "/branches" type handler struct { logger *logging.Logger repository Repository + provinces province.Repository } -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: 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) @@ -67,6 +71,69 @@ func (h *handler) list(c *gin.Context) { 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 @@ -222,6 +289,18 @@ func parseID(raw string) (int64, bool) { 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 diff --git a/internal/org/province/db/postgresql.go b/internal/org/province/db/postgresql.go index 60b4ad0..d5684c3 100644 --- a/internal/org/province/db/postgresql.go +++ b/internal/org/province/db/postgresql.go @@ -42,6 +42,76 @@ func (r *repository) List(ctx context.Context, filter province.ListFilter) (prov return province.ListProvinceDTO{Count: count, Provinces: items}, nil } +func (r *repository) ListRegions(ctx context.Context, activeOnly bool) (province.ListRegionsDTO, error) { + query := `SELECT DISTINCT region FROM provinces` + var args []interface{} + if activeOnly { + query += ` WHERE active = $1` + args = append(args, true) + } + query += ` ORDER BY region->>'tm', region->>'en', region->>'ru'` + + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return province.ListRegionsDTO{}, err + } + defer rows.Close() + + regions := make([]province.LocalizedName, 0) + for rows.Next() { + var regionJSON []byte + if err := rows.Scan(®ionJSON); err != nil { + return province.ListRegionsDTO{}, err + } + var region province.LocalizedName + if err := json.Unmarshal(regionJSON, ®ion); err != nil { + return province.ListRegionsDTO{}, err + } + regions = append(regions, region) + } + if err := rows.Err(); err != nil { + return province.ListRegionsDTO{}, err + } + + return province.ListRegionsDTO{Regions: regions}, nil +} + +func (r *repository) ListEtrapsByRegion(ctx context.Context, region string, activeOnly bool) (province.ListEtrapsDTO, error) { + args := []interface{}{region} + conditions := []string{`( + LOWER(region->>'en') = LOWER($1) + OR LOWER(region->>'ru') = LOWER($1) + OR LOWER(region->>'tm') = LOWER($1) + )`} + if activeOnly { + args = append(args, true) + conditions = append(conditions, fmt.Sprintf("active = $%d", len(args))) + } + + where := " WHERE " + strings.Join(conditions, " AND ") + query := `SELECT ` + provinceSelectColumns + ` FROM provinces` + where + ` ORDER BY name->>'tm', name->>'en', id` + + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return province.ListEtrapsDTO{}, err + } + defer rows.Close() + + etraps := make([]province.ProvinceDTO, 0) + for rows.Next() { + item, err := scanProvince(rows) + if err != nil { + return province.ListEtrapsDTO{}, err + } + etraps = append(etraps, item) + } + if err := rows.Err(); err != nil { + return province.ListEtrapsDTO{}, err + } + + return province.ListEtrapsDTO{Count: int64(len(etraps)), Etraps: etraps}, nil +} + func buildListQuery(filter province.ListFilter) (whereClause string, args []interface{}) { var conditions []string diff --git a/internal/org/province/dto.go b/internal/org/province/dto.go index 0598e56..f74fead 100644 --- a/internal/org/province/dto.go +++ b/internal/org/province/dto.go @@ -37,3 +37,12 @@ type ListProvinceDTO struct { Count int64 `json:"count"` Provinces []ProvinceDTO `json:"provinces"` } + +type ListRegionsDTO struct { + Regions []LocalizedName `json:"regions"` +} + +type ListEtrapsDTO struct { + Count int64 `json:"count"` + Etraps []ProvinceDTO `json:"etraps"` +} diff --git a/internal/org/province/handler.go b/internal/org/province/handler.go index 5bcb777..b6ef711 100644 --- a/internal/org/province/handler.go +++ b/internal/org/province/handler.go @@ -28,6 +28,8 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler 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) @@ -66,6 +68,69 @@ func (h *handler) list(c *gin.Context) { 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 @@ -208,6 +273,18 @@ func parseID(raw string) (int64, bool) { 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 diff --git a/internal/org/province/storage.go b/internal/org/province/storage.go index a5b5ee3..59eab28 100644 --- a/internal/org/province/storage.go +++ b/internal/org/province/storage.go @@ -4,6 +4,8 @@ import "context" type Repository interface { List(ctx context.Context, filter ListFilter) (ListProvinceDTO, error) + ListRegions(ctx context.Context, activeOnly bool) (ListRegionsDTO, error) + ListEtrapsByRegion(ctx context.Context, region string, activeOnly bool) (ListEtrapsDTO, error) GetByID(ctx context.Context, id int64) (ProvinceDTO, error) Create(ctx context.Context, dto CreateProvinceDTO) (ProvinceDTO, error) Update(ctx context.Context, id int64, dto UpdateProvinceDTO) (ProvinceDTO, error) diff --git a/internal/org/router.go b/internal/org/router.go index ff3ae29..537b651 100644 --- a/internal/org/router.go +++ b/internal/org/router.go @@ -23,8 +23,9 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging } func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { + provinceRepo := provincedb.NewRepository(client, logger) return []handlers.Handler{ - province.NewHandler(logger, provincedb.NewRepository(client, logger)), - branches.NewHandler(logger, branchesdb.NewRepository(client, logger)), + province.NewHandler(logger, provinceRepo), + branches.NewHandler(logger, branchesdb.NewRepository(client, logger), provinceRepo), } }