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 branchFromClause = ` FROM branches b LEFT JOIN provinces p ON p.id = b.province_id` const branchSelectColumns = `b.id, b.unique_code, b.name, b.address, b.region, b.province_id, p.name, b.phone_numbers, b.billing_username, b.billing_password, b.billing_sber_username, b.billing_sber_password, b.billing_visa_master_username, b.billing_visa_master_password, b.billing_swift_username, b.billing_swift_password, b.active` const branchReturningColumns = `id, unique_code, name, address, region, province_id, phone_numbers, billing_username, billing_password, billing_sber_username, billing_sber_password, billing_visa_master_username, billing_visa_master_password, billing_swift_username, billing_swift_password, active` const branchReturnedSelectColumns = `i.id, i.unique_code, i.name, i.address, i.region, i.province_id, p.name, i.phone_numbers, i.billing_username, i.billing_password, i.billing_sber_username, i.billing_sber_password, i.billing_visa_master_username, i.billing_visa_master_password, i.billing_swift_username, i.billing_swift_password, i.active` const branchUpdatedSelectColumns = `u.id, u.unique_code, u.name, u.address, u.region, u.province_id, p.name, u.phone_numbers, u.billing_username, u.billing_password, u.billing_sber_username, u.billing_sber_password, u.billing_visa_master_username, u.billing_visa_master_password, u.billing_swift_username, u.billing_swift_password, u.active` func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) { whereClause, args := buildListQuery(filter) var count int64 countQuery := `SELECT COUNT(*)` + branchFromClause + 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`, branchSelectColumns, branchFromClause, 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) (whereClause string, args []interface{}) { 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.ProvinceName != "" { args = append(args, likePattern(filter.ProvinceName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( p.name->>'en' ILIKE $%[1]d OR p.name->>'ru' ILIKE $%[1]d OR p.name->>'tm' ILIKE $%[1]d )`, n)) } if filter.BranchName != "" { args = append(args, likePattern(filter.BranchName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d )`, n)) } if filter.UniqueCode != "" { args = append(args, likePattern(filter.UniqueCode)) n := len(args) conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n)) } if len(conditions) == 0 { return "", args } return " 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%s WHERE b.id = $1`, branchSelectColumns, branchFromClause) 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.ensureProvince(ctx, dto.ProvinceId); err != nil { return branches.BranchDTO{}, err } name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers) if err != nil { return branches.BranchDTO{}, err } active := true if dto.Active != nil { active = *dto.Active } query := ` WITH inserted AS ( INSERT INTO branches ( unique_code, name, address, region, province_id, phone_numbers, billing_username, billing_password, billing_sber_username, billing_sber_password, billing_visa_master_username, billing_visa_master_password, billing_swift_username, billing_swift_password, active ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16) RETURNING ` + branchReturningColumns + ` ) SELECT ` + branchReturnedSelectColumns + ` FROM inserted i LEFT JOIN provinces p ON p.id = i.province_id` row := r.client.QueryRow(ctx, query, nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers, dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword, dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword, dto.BillingSwiftUsername, dto.BillingSwiftPassword, active, ) item, err := scanBranch(row) if isUniqueViolation(err) { return branches.BranchDTO{}, fmt.Errorf("unique code already exists") } return item, err } func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) { if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil { return branches.BranchDTO{}, err } name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers) if err != nil { return branches.BranchDTO{}, err } query := ` WITH updated AS ( UPDATE branches SET unique_code = $1, name = $2, address = $3, region = $4, province_id = $5, phone_numbers = $6, billing_username = $7, billing_password = $8, billing_sber_username = $9, billing_sber_password = $10, billing_visa_master_username = $11, billing_visa_master_password = $12, billing_swift_username = $13, billing_swift_password = $14, active = $15 WHERE id = $16 RETURNING ` + branchReturningColumns + ` ) SELECT ` + branchUpdatedSelectColumns + ` FROM updated u LEFT JOIN provinces p ON p.id = u.province_id` row := r.client.QueryRow(ctx, query, nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers, dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword, dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword, dto.BillingSwiftUsername, dto.BillingSwiftPassword, dto.Active, id, ) item, err := scanBranch(row) if errors.Is(err, pgx.ErrNoRows) { return branches.BranchDTO{}, err } if isUniqueViolation(err) { return branches.BranchDTO{}, fmt.Errorf("unique code 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) ensureProvince(ctx context.Context, provinceID *int64) error { if provinceID == nil { return nil } var id int64 err := r.client.QueryRow(ctx, `SELECT id FROM provinces WHERE id = $1`, *provinceID, ).Scan(&id) if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("province not found") } return err } func marshalBranchJSON(name, address branches.LocalizedText, phoneNumbers []string) ([]byte, []byte, []byte, error) { nameJSON, err := json.Marshal(name) if err != nil { return nil, nil, nil, err } addressJSON, err := json.Marshal(address) if err != nil { return nil, nil, nil, err } if phoneNumbers == nil { phoneNumbers = []string{} } phoneNumbersJSON, err := json.Marshal(phoneNumbers) if err != nil { return nil, nil, nil, err } return nameJSON, addressJSON, phoneNumbersJSON, nil } func nullIfEmpty(value string) interface{} { if value == "" { return nil } return value } 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 nameJSON, addressJSON, provinceNameJSON, phoneNumbersJSON []byte var uniqueCode *string err := row.Scan( &item.Id, &uniqueCode, &nameJSON, &addressJSON, &item.Region, &item.ProvinceId, &provinceNameJSON, &phoneNumbersJSON, &item.BillingUsername, &item.BillingPassword, &item.BillingSberUsername, &item.BillingSberPassword, &item.BillingVisaMasterUsername, &item.BillingVisaMasterPassword, &item.BillingSwiftUsername, &item.BillingSwiftPassword, &item.Active, ) if err != nil { return branches.BranchDTO{}, err } if uniqueCode != nil { item.UniqueCode = *uniqueCode } if err := json.Unmarshal(nameJSON, &item.Name); err != nil { return branches.BranchDTO{}, err } if err := json.Unmarshal(addressJSON, &item.Address); err != nil { return branches.BranchDTO{}, err } if provinceNameJSON != nil { if err := json.Unmarshal(provinceNameJSON, &item.ProvinceName); err != nil { return branches.BranchDTO{}, err } } if err := json.Unmarshal(phoneNumbersJSON, &item.PhoneNumbers); err != nil { return branches.BranchDTO{}, err } if item.PhoneNumbers == nil { item.PhoneNumbers = []string{} } return item, nil }