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.title, c.content, c.status` 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 payment_cards c` var conditions []string if filter.CardName != "" { args = append(args, likePattern(filter.CardName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( c.title->>'en' ILIKE $%[1]d OR c.title->>'ru' ILIKE $%[1]d OR c.title->>'tm' ILIKE $%[1]d )`, n)) } if filter.Status != nil { args = append(args, *filter.Status) conditions = append(conditions, fmt.Sprintf("c.status = $%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 payment_cards 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) { title, content, err := marshalJSON(dto.Title, dto.Content) if err != nil { return paymentcard.PaymentCardDTO{}, err } status := true if dto.Status != nil { status = *dto.Status } query := fmt.Sprintf(` INSERT INTO payment_cards (price, title, content, status) VALUES ($1, $2, $3, $4) RETURNING %s`, cardColumns) return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, status)) } func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.UpdatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) { title, content, err := marshalJSON(dto.Title, dto.Content) if err != nil { return paymentcard.PaymentCardDTO{}, err } query := fmt.Sprintf(` UPDATE payment_cards SET price = $1, title = $2, content = $3, status = $4 WHERE id = $5 RETURNING %s`, cardColumns) item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, dto.Status, id)) if errors.Is(err, pgx.ErrNoRows) { return paymentcard.PaymentCardDTO{}, err } return item, err } func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (paymentcard.PaymentCardDTO, error) { query := fmt.Sprintf(` UPDATE payment_cards SET status = $1 WHERE id = $2 RETURNING %s`, cardColumns) item, err := scanPaymentCard(r.client.QueryRow(ctx, query, status, 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 payment_cards WHERE id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return pgx.ErrNoRows } return nil } func marshalJSON(title, content paymentcard.LocalizedText) ([]byte, []byte, error) { titleJSON, err := json.Marshal(title) if err != nil { return nil, nil, err } contentJSON, err := json.Marshal(content) if err != nil { return nil, nil, err } return titleJSON, contentJSON, nil } type scannable interface { Scan(dest ...interface{}) error } func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) { var item paymentcard.PaymentCardDTO var titleJSON, contentJSON []byte if err := row.Scan( &item.Id, &item.Price, &titleJSON, &contentJSON, &item.Status, ); err != nil { return paymentcard.PaymentCardDTO{}, err } if err := json.Unmarshal(titleJSON, &item.Title); err != nil { return paymentcard.PaymentCardDTO{}, err } if err := json.Unmarshal(contentJSON, &item.Content); err != nil { return paymentcard.PaymentCardDTO{}, err } return item, nil }