Add province-scoped branches for loan paid letters and harden loans.user_id.

Expose GET /loan-paid-off-letters/branches?province_id= for form pickers, require loans.user_id, and proxy the Vite frontend under /online/.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-12 19:12:49 +05:00
parent 1987d4f596
commit 5f6ddc5217
14 changed files with 172 additions and 343 deletions

View File

@@ -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,

View File

@@ -0,0 +1,2 @@
ALTER TABLE loans
ALTER COLUMN user_id DROP NOT NULL;

View File

@@ -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;

View File

@@ -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');
-- ---------------------------------------------------------------------------

View File

@@ -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": [

View File

@@ -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": [

View File

@@ -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

View File

@@ -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)
}

View File

@@ -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"`
}

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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 {

View File

@@ -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

View File

@@ -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/ {