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

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