Files
online-backend/internal/lending/loansrepayment/db/postgresql.go
GuwandykA d7cdd53597 Return role IDs on users and related names on loan APIs.
Loan orders, paid-off letters, and repayments now include user, branch, type, and document names alongside foreign-key IDs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 11:58:15 +05:00

151 lines
4.8 KiB
Go

package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/lending/loansrepayment"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[loansrepayment.LoanRepaymentDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) loansrepayment.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "loans", loanReturningColumns, scanLoanRepayment),
logger: logger,
}
}
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const loanFromClause = ` FROM loans l
LEFT JOIN users u ON u.id = l.user_id`
const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account_number, l.created_at, l.updated_at, ` + userDisplaySQL
const loanReturningColumns = `id, user_id, passport_serie, passport_id, account_number, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter) (loansrepayment.ListLoanRepaymentDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM loans l`+whereClause, args...).Scan(&count); err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`,
loanColumns, loanFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
defer rows.Close()
var items []loansrepayment.LoanRepaymentDTO
for rows.Next() {
item, err := scanLoanRepayment(rows)
if err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loansrepayment.ListLoanRepaymentDTO{}, err
}
return loansrepayment.ListLoanRepaymentDTO{Count: count, Loans: items}, nil
}
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PassportId != "" {
args = append(args, likePattern(filter.PassportId))
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%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) (loansrepayment.LoanRepaymentDTO, error) {
query := `SELECT ` + loanColumns + loanFromClause + ` WHERE l.id = $1`
return scanLoanRepayment(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto loansrepayment.CreateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
query := `
WITH inserted AS (
INSERT INTO loans (user_id, passport_serie, passport_id, account_number)
VALUES ($1, $2, $3, $4)
RETURNING ` + loanReturningColumns + `
)
SELECT ` + loanColumns + `
FROM inserted l
LEFT JOIN users u ON u.id = l.user_id`
return scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber))
}
func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.UpdateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
query := `
WITH updated AS (
UPDATE loans SET
user_id = $1, passport_serie = $2, passport_id = $3, account_number = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5
RETURNING ` + loanReturningColumns + `
)
SELECT ` + loanColumns + `
FROM updated l
LEFT JOIN users u ON u.id = l.user_id`
item, err := scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber, id))
if errors.Is(err, pgx.ErrNoRows) {
return loansrepayment.LoanRepaymentDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func scanLoanRepayment(row genericrepo.Scanner) (loansrepayment.LoanRepaymentDTO, error) {
var item loansrepayment.LoanRepaymentDTO
if err := row.Scan(
&item.Id, &item.UserId, &item.PassportSerie, &item.PassportId, &item.AccountNumber, &item.CreatedAt, &item.UpdatedAt, &item.UserName,
); err != nil {
return loansrepayment.LoanRepaymentDTO{}, err
}
return item, nil
}