diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index 4f6b2aa..7d647a6 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -216,7 +216,7 @@ CREATE TABLE IF NOT EXISTS loan_orders ( CREATE TABLE IF NOT EXISTS loans ( id bigserial PRIMARY KEY, - user_id bigint, + user_id bigint NOT NULL, passport_serie character varying(255) NOT NULL, passport_id character varying(255) NOT NULL, account_number character varying(255) NOT NULL, diff --git a/db/migrations/20260811082731_loans_user_id_not_null.down.sql b/db/migrations/20260811082731_loans_user_id_not_null.down.sql new file mode 100644 index 0000000..f8ebc83 --- /dev/null +++ b/db/migrations/20260811082731_loans_user_id_not_null.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE loans + ALTER COLUMN user_id DROP NOT NULL; diff --git a/db/migrations/20260811082731_loans_user_id_not_null.up.sql b/db/migrations/20260811082731_loans_user_id_not_null.up.sql new file mode 100644 index 0000000..fe4b3ec --- /dev/null +++ b/db/migrations/20260811082731_loans_user_id_not_null.up.sql @@ -0,0 +1,10 @@ +-- Require loans.user_id; backfill any existing NULLs to the first user. +UPDATE loans +SET user_id = (SELECT id FROM users ORDER BY id ASC LIMIT 1) +WHERE user_id IS NULL + AND EXISTS (SELECT 1 FROM users); + +DELETE FROM loans WHERE user_id IS NULL; + +ALTER TABLE loans + ALTER COLUMN user_id SET NOT NULL; diff --git a/db/seed.sql b/db/seed.sql index 048029b..3f5dfb6 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -533,7 +533,7 @@ INSERT INTO loan_orders ( INSERT INTO loans (user_id, passport_serie, passport_id, account_number) VALUES (2, 'I-AG', '778899', 'ACC-LOAN-10001'), (3, 'I-MR', '998877', 'ACC-LOAN-10002'), - (NULL, 'I-AG', '101010', 'ACC-LOAN-10003'), + (1, 'I-AG', '101010', 'ACC-LOAN-10003'), (2, 'I-AG', '303030', 'ACC-LOAN-10004'); -- --------------------------------------------------------------------------- diff --git a/docs/docs.go b/docs/docs.go index ad4e432..d7c11ec 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -1985,6 +1985,12 @@ const docTemplate = `{ "name": "passport_id", "in": "query" }, + { + "type": "string", + "description": "Filter by customer name", + "name": "name", + "in": "query" + }, { "type": "string", "description": "Filter by status", @@ -4163,105 +4169,6 @@ 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 81aba00..d349eda 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1979,6 +1979,12 @@ "name": "passport_id", "in": "query" }, + { + "type": "string", + "description": "Filter by customer name", + "name": "name", + "in": "query" + }, { "type": "string", "description": "Filter by status", @@ -4157,105 +4163,6 @@ } } }, - "/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 8b3516f..e7f5aed 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -2476,6 +2476,10 @@ paths: in: query name: passport_id type: string + - description: Filter by customer name + in: query + name: name + type: string - description: Filter by status in: query name: status @@ -3981,69 +3985,6 @@ 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/lending/loanpaidletter/db/postgresql.go b/internal/lending/loanpaidletter/db/postgresql.go index 41e19d9..0eabb40 100644 --- a/internal/lending/loanpaidletter/db/postgresql.go +++ b/internal/lending/loanpaidletter/db/postgresql.go @@ -2,6 +2,7 @@ package db import ( "context" + "encoding/json" "fmt" "strings" @@ -80,6 +81,14 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args conditions = append(conditions, fmt.Sprintf("passport_id ILIKE $%d", len(args))) } + if filter.Name != "" { + args = append(args, likePattern(filter.Name)) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`( + customer_name ILIKE $%[1]d OR customer_surname ILIKE $%[1]d OR COALESCE(customer_patronic_name, '') ILIKE $%[1]d + )`, n)) + } + if filter.Status != nil { args = append(args, *filter.Status) conditions = append(conditions, fmt.Sprintf("status = $%d", len(args))) @@ -109,6 +118,46 @@ func likePattern(term string) string { return "%" + term + "%" } +func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (loanpaidletter.ListBranchesByProvinceDTO, error) { + args := []interface{}{provinceID} + where := ` WHERE province_id = $1` + if activeOnly { + where += ` AND active = true` + } + + query := ` + SELECT id, COALESCE(unique_code, ''), name, region, province_id, active + FROM branches` + where + ` + ORDER BY name->>'tm', name->>'en', id` + + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return loanpaidletter.ListBranchesByProvinceDTO{}, err + } + defer rows.Close() + + branches := make([]loanpaidletter.BranchByProvinceDTO, 0) + for rows.Next() { + var item loanpaidletter.BranchByProvinceDTO + var nameJSON []byte + if err := rows.Scan(&item.Id, &item.UniqueCode, &nameJSON, &item.Region, &item.ProvinceId, &item.Active); err != nil { + return loanpaidletter.ListBranchesByProvinceDTO{}, err + } + if err := json.Unmarshal(nameJSON, &item.Name); err != nil { + return loanpaidletter.ListBranchesByProvinceDTO{}, err + } + branches = append(branches, item) + } + if err := rows.Err(); err != nil { + return loanpaidletter.ListBranchesByProvinceDTO{}, err + } + + return loanpaidletter.ListBranchesByProvinceDTO{ + Count: int64(len(branches)), + Branches: branches, + }, nil +} + func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) { return r.generic.GetByID(ctx, id) } diff --git a/internal/lending/loanpaidletter/dto.go b/internal/lending/loanpaidletter/dto.go index bc83135..99333aa 100644 --- a/internal/lending/loanpaidletter/dto.go +++ b/internal/lending/loanpaidletter/dto.go @@ -70,6 +70,7 @@ type UpdateLoanPaidLetterDTO struct { type ListFilter struct { PassportId string + Name string Status *string BranchId *int64 Region string @@ -81,3 +82,24 @@ type ListLoanPaidLetterDTO struct { Count int64 `json:"count"` LoanPaidLetters []LoanPaidLetterDTO `json:"loanPaidLetters"` } + +type LocalizedText struct { + En string `json:"en"` + Ru string `json:"ru"` + Tm string `json:"tm"` +} + +// BranchByProvinceDTO is a compact branch row for province-scoped pickers. +type BranchByProvinceDTO struct { + Id int64 `json:"id"` + UniqueCode string `json:"uniqueCode"` + Name LocalizedText `json:"name"` + Region string `json:"region"` + ProvinceId *int64 `json:"provinceId"` + Active bool `json:"active"` +} + +type ListBranchesByProvinceDTO struct { + Count int64 `json:"count"` + Branches []BranchByProvinceDTO `json:"branches"` +} diff --git a/internal/lending/loanpaidletter/handler.go b/internal/lending/loanpaidletter/handler.go index 69079a3..e9ffedb 100644 --- a/internal/lending/loanpaidletter/handler.go +++ b/internal/lending/loanpaidletter/handler.go @@ -28,6 +28,7 @@ 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("/branches", h.listBranchesByProvince) group.GET("/:id", h.getByID) group.POST("", h.create) group.PUT("/:id", h.update) @@ -41,6 +42,7 @@ func (h *handler) Register(router *gin.RouterGroup) { // @Produce json // @Security BearerAuth // @Param passport_id query string false "Filter by passport ID" +// @Param name query string false "Filter by customer name" // @Param status query string false "Filter by status" // @Param branch_id query int false "Filter by branch ID" // @Param region query string false "Filter by region" @@ -67,6 +69,45 @@ func (h *handler) list(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } +// listBranchesByProvince godoc +// @Summary List branches by province +// @Description Returns branches for the selected province (etrap) id for loan paid-off letter forms +// @Tags loan-paid-off-letters +// @Produce json +// @Security BearerAuth +// @Param province_id query int true "Province ID" +// @Param active query bool false "Only active branches" default(true) +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /loan-paid-off-letters/branches [get] +func (h *handler) listBranchesByProvince(c *gin.Context) { + provinceID, ok := parseID(c.Query("province_id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + activeOnly := true + if raw := c.Query("active"); raw != "" { + active, err := strconv.ParseBool(raw) + if err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + activeOnly = active + } + + result, err := h.repository.ListBranchesByProvince(c.Request.Context(), provinceID, activeOnly) + if err != nil { + h.logger.Errorf("list branches by province failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + // getByID godoc // @Summary Get loan paid off letter by ID // @Description Returns a single loan paid off letter @@ -241,6 +282,10 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.PassportId = raw } + if raw := strings.TrimSpace(c.Query("name")); raw != "" { + filter.Name = raw + } + if raw := strings.TrimSpace(c.Query("status")); raw != "" { filter.Status = &raw } diff --git a/internal/lending/loanpaidletter/storage.go b/internal/lending/loanpaidletter/storage.go index 14d2316..e4aeb2e 100644 --- a/internal/lending/loanpaidletter/storage.go +++ b/internal/lending/loanpaidletter/storage.go @@ -4,6 +4,7 @@ import "context" type Repository interface { List(ctx context.Context, filter ListFilter) (ListLoanPaidLetterDTO, error) + ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (ListBranchesByProvinceDTO, error) GetByID(ctx context.Context, id int64) (LoanPaidLetterDTO, error) Create(ctx context.Context, dto CreateLoanPaidLetterDTO) (LoanPaidLetterDTO, error) Update(ctx context.Context, id int64, dto UpdateLoanPaidLetterDTO) (LoanPaidLetterDTO, error) diff --git a/internal/org/province/db/postgresql.go b/internal/org/province/db/postgresql.go index d5684c3..c24b4fb 100644 --- a/internal/org/province/db/postgresql.go +++ b/internal/org/province/db/postgresql.go @@ -43,13 +43,13 @@ func (r *repository) List(ctx context.Context, filter province.ListFilter) (prov } func (r *repository) ListRegions(ctx context.Context, activeOnly bool) (province.ListRegionsDTO, error) { - query := `SELECT DISTINCT region FROM provinces` + inner := `SELECT DISTINCT region::jsonb AS region FROM provinces` var args []interface{} if activeOnly { - query += ` WHERE active = $1` + inner += ` WHERE active = $1` args = append(args, true) } - query += ` ORDER BY region->>'tm', region->>'en', region->>'ru'` + query := `SELECT region FROM (` + inner + `) AS distinct_regions ORDER BY region->>'tm', region->>'en', region->>'ru'` rows, err := r.client.Query(ctx, query, args...) if err != nil { diff --git a/internal/org/province/handler.go b/internal/org/province/handler.go index b6ef711..943ffc9 100644 --- a/internal/org/province/handler.go +++ b/internal/org/province/handler.go @@ -28,8 +28,9 @@ 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) + // Use /branches/regions and /branches/etraps instead. + // group.GET("/regions", h.listRegions) + // group.GET("/etraps", h.listEtraps) group.GET("/:id", h.getByID) group.POST("", h.create) group.PUT("/:id", h.update) @@ -68,69 +69,6 @@ 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 @@ -273,18 +211,6 @@ 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/nginx/test.webulgam.com.conf b/nginx/test.webulgam.com.conf index 63781ed..49b4aa2 100644 --- a/nginx/test.webulgam.com.conf +++ b/nginx/test.webulgam.com.conf @@ -58,6 +58,25 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } + # --- online frontend (Vite) → :5173 --- + # Example: https://test.webulgam.com/online/ + # Do NOT strip /online — Vite base is /online/, stripping causes a 302 loop. + location = /online { + return 301 /online/; + } + + location /online/ { + proxy_pass http://127.0.0.1:5173; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + # Vite HMR / WebSocket + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + } + # --- online-backend → :5005 --- # Example: https://test.webulgam.com/online-backend/api/admin/... location /online-backend/ {