package db import ( "context" "errors" "fmt" "strings" "online-back/internal/currency" "online-back/internal/shared" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" "github.com/jackc/pgconn" "github.com/jackc/pgx/v4" ) type repository struct { client postgresql.Client generic *genericrepo.Repository[currency.CurrencyDTO] logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) currency.Repository { return &repository{ client: client, generic: genericrepo.New(client, "currencies", currencyColumnsSQL, scanCurrency), logger: logger, } } var currencyColumns = []string{ "id", "currency_from", "currency_to", "value", "created_by", "updated_by", "created_at", "updated_at", } var currencyColumnsSQL = strings.Join(currencyColumns, ", ") const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', %s.first_name, %s.last_name)), ''), NULLIF(%s.name, ''), %s.username, '')` const currencyFromClause = ` FROM currencies c LEFT JOIN users cu ON cu.id = c.created_by LEFT JOIN users uu ON uu.id = c.updated_by` var currencySelectColumns = shared.PrefixedColumns("c", currencyColumns) + `, ` + fmt.Sprintf(userDisplaySQL, "cu", "cu", "cu", "cu") + `, COALESCE(cu.username, ''), COALESCE(cu.phone, ''), COALESCE(cu.email, ''), ` + fmt.Sprintf(userDisplaySQL, "uu", "uu", "uu", "uu") + `, COALESCE(uu.username, ''), COALESCE(uu.phone, ''), COALESCE(uu.email, '')` func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) { whereClause, args := buildListQuery(filter) var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM currencies c`+whereClause, args...).Scan(&count); err != nil { return currency.ListCurrencyDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 query := fmt.Sprintf( `SELECT %s%s%s ORDER BY c.id DESC LIMIT $%d OFFSET $%d`, currencySelectColumns, currencyFromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...) if err != nil { return currency.ListCurrencyDTO{}, err } defer rows.Close() var items []currency.CurrencyDTO for rows.Next() { item, err := scanCurrencyWithUsers(rows) if err != nil { return currency.ListCurrencyDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return currency.ListCurrencyDTO{}, err } return currency.ListCurrencyDTO{Count: count, Currencies: items}, nil } func buildListQuery(filter currency.ListFilter) (whereClause string, args []interface{}) { conditions := []string{"c.deleted_at IS NULL"} if filter.Search != "" { args = append(args, shared.LikePattern(filter.Search)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\' )`, n)) } if filter.CurrencyFrom != "" { args = append(args, filter.CurrencyFrom) conditions = append(conditions, fmt.Sprintf("c.currency_from = $%d", len(args))) } if filter.CurrencyTo != "" { args = append(args, filter.CurrencyTo) conditions = append(conditions, fmt.Sprintf("c.currency_to = $%d", len(args))) } return " WHERE " + strings.Join(conditions, " AND "), args } func (r *repository) GetByID(ctx context.Context, id int64) (currency.CurrencyDTO, error) { query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL` return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id)) } func (r *repository) Create(ctx context.Context, dto currency.CreateCurrencyDTO) (currency.CurrencyDTO, error) { from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value) query := ` WITH inserted AS ( INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by) VALUES ($1, $2, $3::numeric, $4, $4) RETURNING ` + currencyColumnsSQL + ` ) SELECT ` + currencySelectColumns + ` FROM inserted c LEFT JOIN users cu ON cu.id = c.created_by LEFT JOIN users uu ON uu.id = c.updated_by` item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy)) if isUniqueViolation(err) { return currency.CurrencyDTO{}, currency.ErrDuplicate } return item, err } func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) { from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value) query := ` WITH updated AS ( UPDATE currencies SET currency_from = $1, currency_to = $2, value = $3::numeric, updated_by = $4, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $5 AND deleted_at IS NULL RETURNING ` + currencyColumnsSQL + ` ) SELECT ` + currencySelectColumns + ` FROM updated c LEFT JOIN users cu ON cu.id = c.created_by LEFT JOIN users uu ON uu.id = c.updated_by` item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.UpdatedBy, id)) if errors.Is(err, pgx.ErrNoRows) { return currency.CurrencyDTO{}, err } if isUniqueViolation(err) { return currency.CurrencyDTO{}, currency.ErrDuplicate } return item, err } func (r *repository) Delete(ctx context.Context, id int64) error { return r.generic.Delete(ctx, id) } // isUniqueViolation reports whether err is a Postgres unique-constraint // violation (e.g. the currencies_from_to_idx partial unique index rejecting // a duplicate active currency_from/currency_to pair), so callers can map it // to a clean 409 instead of letting it fall through as a generic 500. func isUniqueViolation(err error) bool { var pgErr *pgconn.PgError return errors.As(err, &pgErr) && pgErr.Code == "23505" } func normalizeRate(from, to string, value currency.RateValue) (string, string, string) { return strings.ToUpper(strings.TrimSpace(from)), strings.ToUpper(strings.TrimSpace(to)), strings.TrimSpace(value.String()) } func scanCurrency(row genericrepo.Scanner) (currency.CurrencyDTO, error) { return scanCurrencyRow(row, false) } func scanCurrencyWithUsers(row genericrepo.Scanner) (currency.CurrencyDTO, error) { return scanCurrencyRow(row, true) } func scanCurrencyRow(row genericrepo.Scanner, withUsers bool) (currency.CurrencyDTO, error) { var item currency.CurrencyDTO var value string dest := []interface{}{ &item.Id, &item.CurrencyFrom, &item.CurrencyTo, &value, &item.CreatedById, &item.UpdatedById, &item.CreatedAt, &item.UpdatedAt, } var createdName, createdUsername, createdPhone, createdEmail string var updatedName, updatedUsername, updatedPhone, updatedEmail string if withUsers { dest = append(dest, &createdName, &createdUsername, &createdPhone, &createdEmail, &updatedName, &updatedUsername, &updatedPhone, &updatedEmail, ) } if err := row.Scan(dest...); err != nil { return currency.CurrencyDTO{}, err } item.Value = currency.RateValue(trimNumeric(value)) if withUsers { item.CreatedBy = userInfo(item.CreatedById, createdName, createdUsername, createdPhone, createdEmail) item.UpdatedBy = userInfo(item.UpdatedById, updatedName, updatedUsername, updatedPhone, updatedEmail) } return item, nil } func userInfo(id *int64, name, username, phone, email string) *currency.UserInfo { if id == nil { return nil } return ¤cy.UserInfo{ Id: *id, Name: name, Username: username, Phone: phone, Email: email, } } func trimNumeric(raw string) string { raw = strings.TrimSpace(raw) if !strings.Contains(raw, ".") { return raw } raw = strings.TrimRight(raw, "0") raw = strings.TrimRight(raw, ".") if raw == "" { return "0" } return raw }