package db import ( "context" "encoding/json" "errors" "fmt" "strings" "online-back/internal/admin/paymentcard" "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) paymentcard.Repository { return &repository{client: client, logger: logger} } const cardColumns = `c.id, c.price, c.name, c.notes, c.active` const cardReturningColumns = `id, price, name, notes, active` func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) { fromClause, whereClause, args := buildListQuery(filter) var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { return paymentcard.ListPaymentCardDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 listQuery := fmt.Sprintf( `SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`, cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) if err != nil { return paymentcard.ListPaymentCardDTO{}, err } defer rows.Close() var items []paymentcard.PaymentCardDTO for rows.Next() { item, err := scanPaymentCard(rows) if err != nil { return paymentcard.ListPaymentCardDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return paymentcard.ListPaymentCardDTO{}, err } return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil } func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) { fromClause = ` FROM card_types c` var conditions []string if filter.CardName != "" { args = append(args, likePattern(filter.CardName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( c.name->>'en' ILIKE $%[1]d OR c.name->>'ru' ILIKE $%[1]d OR c.name->>'tm' ILIKE $%[1]d )`, n)) } if filter.Active != nil { args = append(args, *filter.Active) conditions = append(conditions, fmt.Sprintf("c.active = $%d", len(args))) } 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) (paymentcard.PaymentCardDTO, error) { query := fmt.Sprintf(`SELECT %s FROM card_types c WHERE c.id = $1`, cardColumns) item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id)) if errors.Is(err, pgx.ErrNoRows) { return paymentcard.PaymentCardDTO{}, err } return item, err } func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) { name, err := marshalName(dto.Title) if err != nil { return paymentcard.PaymentCardDTO{}, err } active := true if dto.Active != nil { active = *dto.Active } query := fmt.Sprintf(` INSERT INTO card_types (price, name, notes, active) VALUES ($1, $2, $3, $4) RETURNING %s`, cardReturningColumns) return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, active)) } func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.UpdatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) { name, err := marshalName(dto.Title) if err != nil { return paymentcard.PaymentCardDTO{}, err } query := fmt.Sprintf(` UPDATE card_types SET price = $1, name = $2, notes = $3, active = $4 WHERE id = $5 RETURNING %s`, cardReturningColumns) item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id)) if errors.Is(err, pgx.ErrNoRows) { return paymentcard.PaymentCardDTO{}, err } return item, err } func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) { query := fmt.Sprintf(` UPDATE card_types SET active = $1 WHERE id = $2 RETURNING %s`, cardReturningColumns) item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id)) if errors.Is(err, pgx.ErrNoRows) { return paymentcard.PaymentCardDTO{}, err } return item, err } func (r *repository) Delete(ctx context.Context, id int64) error { tag, err := r.client.Exec(ctx, `DELETE FROM card_types WHERE id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return pgx.ErrNoRows } return nil } func marshalName(title paymentcard.LocalizedText) ([]byte, error) { return json.Marshal(title) } type scannable interface { Scan(dest ...interface{}) error } func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) { var item paymentcard.PaymentCardDTO var nameJSON []byte if err := row.Scan( &item.Id, &item.Price, &nameJSON, &item.Notes, &item.Active, ); err != nil { return paymentcard.PaymentCardDTO{}, err } if err := json.Unmarshal(nameJSON, &item.Title); err != nil { return paymentcard.PaymentCardDTO{}, err } return item, nil }