change users table

This commit is contained in:
guwandyk committed 2026-07-13 12:11:35 +05:00
1 parent c29c72fd92
commit 6705c4ce91
22 files changed
+3150 -83

No files matched your search

@@ -0,0 +1,210 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/admin/loanpaidletter"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loanpaidletter.Repository {
return &repository{client: client, logger: logger}
}
// letterWritableColumns lists every loan_paid_off_letters column except id, created_at
// and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read.
var letterWritableColumns = []string{
"unique_id", "region", "branch_id", "user_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at",
"phone", "passport_serie", "passport_id",
"status", "notes", "loan_contract_number", "loan_contract_date",
"loan_amount", "loan_reason", "loan_file",
}
var letterColumns = append(append([]string{"id"}, letterWritableColumns...), "created_at", "updated_at")
var letterColumnsSQL = strings.Join(letterColumns, ", ")
var letterWritableColumnsSQL = strings.Join(letterWritableColumns, ", ")
func createArgs(dto loanpaidletter.CreateLoanPaidLetterDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
dto.Phone, dto.PassportSerie, dto.PassportId,
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
}
}
func updateArgs(dto loanpaidletter.UpdateLoanPaidLetterDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
dto.Phone, dto.PassportSerie, dto.PassportId,
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
}
}
func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter) (loanpaidletter.ListLoanPaidLetterDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM loan_paid_off_letters` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM loan_paid_off_letters%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
letterColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
defer rows.Close()
var items []loanpaidletter.LoanPaidLetterDTO
for rows.Next() {
item, err := scanLoanPaidLetter(rows)
if err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loanpaidletter.ListLoanPaidLetterDTO{}, err
}
return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil
}
func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PassportId != "" {
args = append(args, likePattern(filter.PassportId))
conditions = append(conditions, fmt.Sprintf("passport_id ILIKE $%d", len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
}
if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_paid_off_letters WHERE id = $1`, letterColumnsSQL)
item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, id))
if err != nil {
return loanpaidletter.LoanPaidLetterDTO{}, err
}
return item, nil
}
func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
args := createArgs(dto)
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO loan_paid_off_letters (%s) VALUES (%s) RETURNING %s`,
letterWritableColumnsSQL, strings.Join(placeholders, ", "), letterColumnsSQL,
)
return scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.UpdateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(letterWritableColumns))
for i, column := range letterWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE loan_paid_off_letters SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), letterColumnsSQL,
)
item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
if err != nil {
return loanpaidletter.LoanPaidLetterDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_paid_off_letters WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanPaidLetter(row scannable) (loanpaidletter.LoanPaidLetterDTO, error) {
var item loanpaidletter.LoanPaidLetterDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt,
&item.Phone, &item.PassportSerie, &item.PassportId,
&item.Status, &item.Notes, &item.LoanContractNumber, &item.LoanContractDate,
&item.LoanAmount, &item.LoanReason, &item.LoanFile,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
return loanpaidletter.LoanPaidLetterDTO{}, err
}
return item, nil
}
+83
View File
@@ -0,0 +1,83 @@
package loanpaidletter
import "time"
type LoanPaidLetterDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
UserId *int64 `json:"userId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone string `json:"phone"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
Status *string `json:"status"`
Notes *string `json:"notes"`
LoanContractNumber *string `json:"loanContractNumber"`
LoanContractDate *time.Time `json:"loanContractDate"`
LoanAmount *string `json:"loanAmount"`
LoanReason *string `json:"loanReason"`
LoanFile *string `json:"loanFile"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateLoanPaidLetterDTO struct {
UniqueId *string `json:"uniqueId"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
UserId *int64 `json:"userId"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
LoanContractNumber *string `json:"loanContractNumber"`
LoanContractDate *time.Time `json:"loanContractDate"`
LoanAmount *string `json:"loanAmount"`
LoanReason *string `json:"loanReason"`
LoanFile *string `json:"loanFile"`
}
type UpdateLoanPaidLetterDTO struct {
UniqueId *string `json:"uniqueId"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
UserId *int64 `json:"userId"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
LoanContractNumber *string `json:"loanContractNumber"`
LoanContractDate *time.Time `json:"loanContractDate"`
LoanAmount *string `json:"loanAmount"`
LoanReason *string `json:"loanReason"`
LoanFile *string `json:"loanFile"`
}
type ListFilter struct {
PassportId string
Status *string
BranchId *int64
Region string
Page int
Limit int
}
type ListLoanPaidLetterDTO struct {
Count int64 `json:"count"`
LoanPaidLetters []LoanPaidLetterDTO `json:"loanPaidLetters"`
}
+261
View File
@@ -0,0 +1,261 @@
package loanpaidletter
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/loan-paid-off-letters"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List loan paid off letters
// @Description Returns paginated loan paid off letters with optional filters
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param passport_id query string false "Filter by passport ID"
// @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"
// @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 /loan-paid-off-letters [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 loan paid off letters 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
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := 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 loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create loan paid off letter
// @Description Creates a new loan paid off letter
// @Tags loan-paid-off-letters
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateLoanPaidLetterDTO true "Loan paid off letter payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters [post]
func (h *handler) create(c *gin.Context) {
var dto CreateLoanPaidLetterDTO
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 {
h.logger.Errorf("create loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update loan paid off letter
// @Description Updates an existing loan paid off letter
// @Tags loan-paid-off-letters
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Param body body UpdateLoanPaidLetterDTO true "Loan paid off letter payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateLoanPaidLetterDTO
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 {
h.logger.Errorf("update loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete loan paid off letter
// @Description Deletes a loan paid off letter
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := 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 loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("passport_id")); raw != "" {
filter.PassportId = raw
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
if raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
}
return filter, true
}
+11
View File
@@ -0,0 +1,11 @@
package loanpaidletter
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListLoanPaidLetterDTO, 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)
Delete(ctx context.Context, id int64) error
}