Files
online-backend/internal/admin/cardpinorders/db/postgresql.go
2026-07-13 18:47:35 +05:00

205 lines
6.6 KiB
Go

package db
import (
"context"
"fmt"
"strings"
"online-back/internal/admin/cardpinorders"
"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) cardpinorders.Repository {
return &repository{client: client, logger: logger}
}
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
var cardPinOrderWritableColumns = []string{
"unique_id", "user_id", "card_type_id", "card_number", "region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
"status", "notes",
}
var cardPinOrderColumns = append(append([]string{"id"}, cardPinOrderWritableColumns...), "created_at", "updated_at")
var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
}
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
}
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) FROM card_pin_orders` + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM card_pin_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`,
cardPinOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
defer rows.Close()
var items []cardpinorders.CardPinOrderDTO
for rows.Next() {
item, err := scanCardPinOrder(rows)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
}
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
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.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_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 (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM card_pin_orders WHERE id = $1`, cardPinOrderColumnsSQL)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, id))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, 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 card_pin_orders (%s) VALUES (%s) RETURNING %s`,
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
)
return scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardPinOrderWritableColumns))
for i, column := range cardPinOrderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM card_pin_orders 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 scanCardPinOrder(row scannable) (cardpinorders.CardPinOrderDTO, error) {
var item cardpinorders.CardPinOrderDTO
err := row.Scan(
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
&item.Status, &item.Notes,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
return item, nil
}