Files
online-backend/internal/admin/branches/db/postgresql.go
2026-07-04 18:34:30 +05:00

261 lines
7.6 KiB
Go

package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/branches"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Repository {
return &repository{client: client, logger: logger}
}
const branchColumns = `b.id, b.title, b.province_id, b.location_id, b.unikal_nomer, b.address,
b.billing_login, b.billing_password, b.billing_username_sber, b.billing_password_sber,
b.billing_username_visa, b.billing_password_visa`
func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) ` + fromClause + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return branches.ListBranchDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY b.id LIMIT $%d OFFSET $%d`,
branchColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
listArgs := append(args, filter.Limit, offset)
rows, err := r.client.Query(ctx, listQuery, listArgs...)
if err != nil {
return branches.ListBranchDTO{}, err
}
defer rows.Close()
var items []branches.BranchDTO
for rows.Next() {
item, err := scanBranch(rows)
if err != nil {
return branches.ListBranchDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return branches.ListBranchDTO{}, err
}
return branches.ListBranchDTO{Count: count, Branches: items}, nil
}
func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM branches b`
if filter.ProvinceName != "" {
fromClause += ` JOIN province p ON p.id = b.province_id`
}
var conditions []string
if filter.ProvinceID != nil {
args = append(args, *filter.ProvinceID)
conditions = append(conditions, fmt.Sprintf("b.province_id = $%d", len(args)))
}
if filter.LocationID != nil {
args = append(args, *filter.LocationID)
conditions = append(conditions, fmt.Sprintf("b.location_id = $%d", len(args)))
}
if filter.ProvinceName != "" {
args = append(args, likePattern(filter.ProvinceName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
p.title->>'en' ILIKE $%[1]d OR p.title->>'ru' ILIKE $%[1]d OR p.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.BranchName != "" {
args = append(args, likePattern(filter.BranchName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
b.title->>'en' ILIKE $%[1]d OR b.title->>'ru' ILIKE $%[1]d OR b.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.UnikalNomer != "" {
args = append(args, likePattern(filter.UnikalNomer))
n := len(args)
conditions = append(conditions, fmt.Sprintf("b.unikal_nomer ILIKE $%d", n))
}
if len(conditions) == 0 {
return fromClause, "", args
}
return fromClause, " 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) (branches.BranchDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM branches b WHERE b.id = $1`, branchColumns)
row := r.client.QueryRow(ctx, query, id)
item, err := scanBranch(row)
if errors.Is(err, pgx.ErrNoRows) {
return branches.BranchDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (branches.BranchDTO, error) {
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
return branches.BranchDTO{}, err
}
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
query := fmt.Sprintf(`
INSERT INTO branches (
title, province_id, location_id, unikal_nomer, address,
billing_login, billing_password, billing_username_sber, billing_password_sber,
billing_username_visa, billing_password_visa
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa,
)
item, err := scanBranch(row)
if isUniqueViolation(err) {
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
}
return item, err
}
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
return branches.BranchDTO{}, err
}
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
query := fmt.Sprintf(`
UPDATE branches SET
title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5,
billing_login = $6, billing_password = $7, billing_username_sber = $8,
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11
WHERE id = $12
RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa, id,
)
item, err := scanBranch(row)
if errors.Is(err, pgx.ErrNoRows) {
return branches.BranchDTO{}, err
}
if isUniqueViolation(err) {
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM branches WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func (r *repository) ensureRelations(ctx context.Context, provinceID, locationID int64) error {
var id int64
err := r.client.QueryRow(ctx,
`SELECT id FROM location WHERE id = $1 AND province_id = $2`, locationID, provinceID,
).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("location not found in province")
}
return err
}
func marshalBranchJSON(title, address branches.LocalizedText) ([]byte, []byte, error) {
titleJSON, err := json.Marshal(title)
if err != nil {
return nil, nil, err
}
addressJSON, err := json.Marshal(address)
if err != nil {
return nil, nil, err
}
return titleJSON, addressJSON, nil
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanBranch(row scannable) (branches.BranchDTO, error) {
var item branches.BranchDTO
var titleJSON, addressJSON []byte
err := row.Scan(
&item.Id, &titleJSON, &item.ProvinceId, &item.LocationId, &item.UnikalNomer, &addressJSON,
&item.BillingLogin, &item.BillingPassword, &item.BillingUsernameSber, &item.BillingPasswordSber,
&item.BillingUsernameVisa, &item.BillingPasswordVisa,
)
if err != nil {
return branches.BranchDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return branches.BranchDTO{}, err
}
if err := json.Unmarshal(addressJSON, &item.Address); err != nil {
return branches.BranchDTO{}, err
}
return item, nil
}