323 lines
10 KiB
Go
323 lines
10 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"online-back/internal/identity/rbac"
|
|
"online-back/internal/org/branches"
|
|
"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"
|
|
)
|
|
|
|
// regionUniqueCodePrefix maps a branch's region code to the 2-digit prefix
|
|
// its unique_code must start with, so a branch's code always identifies its
|
|
// region at a glance.
|
|
var regionUniqueCodePrefix = map[string]string{
|
|
"AG": "13", // Aşgabat
|
|
"AH": "23", // Ahal
|
|
"BL": "63", // Balkan
|
|
"DZ": "93", // Daşoguz
|
|
"MR": "73", // Mary
|
|
"LB": "83", // Lebap
|
|
}
|
|
|
|
// validateUniqueCode checks that a client-supplied unique_code starts with
|
|
// the 2-digit prefix for the given region (the DTO's "numeric,len=4" binding
|
|
// already guarantees 4 digits).
|
|
func validateUniqueCode(region, code string) error {
|
|
prefix, ok := regionUniqueCodePrefix[region]
|
|
if !ok {
|
|
return fmt.Errorf("unsupported region")
|
|
}
|
|
if !strings.HasPrefix(code, prefix) {
|
|
return fmt.Errorf("unique code must start with %s for region %s", prefix, region)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type repository struct {
|
|
client postgresql.Client
|
|
generic *genericrepo.Repository[branches.BranchDTO]
|
|
logger *logging.Logger
|
|
}
|
|
|
|
func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Repository {
|
|
return &repository{
|
|
client: client,
|
|
generic: genericrepo.New(client, "branches", branchSelectColumns, scanBranch),
|
|
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{}) {
|
|
conditions := []string{"b.deleted_at IS NULL"}
|
|
|
|
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, shared.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, shared.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, shared.LikePattern(filter.UniqueCode))
|
|
n := len(args)
|
|
conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n))
|
|
}
|
|
|
|
if len(filter.BranchIds) > 0 {
|
|
conditions, args = rbac.AppendBranchIDs(conditions, args, "b.id", filter.BranchIds)
|
|
}
|
|
|
|
return " WHERE " + strings.Join(conditions, " AND "), args
|
|
}
|
|
|
|
func (r *repository) GetByID(ctx context.Context, id int64) (branches.BranchDTO, error) {
|
|
query := fmt.Sprintf(`SELECT %s%s WHERE b.id = $1 AND b.deleted_at IS NULL`, 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
|
|
}
|
|
if err := validateUniqueCode(dto.Region, dto.UniqueCode); err != nil {
|
|
return branches.BranchDTO{}, err
|
|
}
|
|
|
|
name, address, err := marshalBranchJSON(dto.Name, dto.Address)
|
|
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)
|
|
RETURNING ` + branchReturningColumns + `
|
|
)
|
|
SELECT ` + branchReturnedSelectColumns + `
|
|
FROM inserted i
|
|
LEFT JOIN provinces p ON p.id = i.province_id`
|
|
|
|
row := r.client.QueryRow(ctx, query,
|
|
dto.UniqueCode, name, address, dto.Region, dto.ProvinceId, dto.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, err := marshalBranchJSON(dto.Name, dto.Address)
|
|
if err != nil {
|
|
return branches.BranchDTO{}, err
|
|
}
|
|
|
|
query := `
|
|
WITH updated AS (
|
|
UPDATE branches SET
|
|
name = $1, address = $2, region = $3, province_id = $4,
|
|
phone_numbers = $5, billing_username = $6, billing_password = $7,
|
|
billing_sber_username = $8, billing_sber_password = $9,
|
|
billing_visa_master_username = $10, billing_visa_master_password = $11,
|
|
billing_swift_username = $12, billing_swift_password = $13, active = $14
|
|
WHERE id = $15 AND deleted_at IS NULL
|
|
RETURNING ` + branchReturningColumns + `
|
|
)
|
|
SELECT ` + branchUpdatedSelectColumns + `
|
|
FROM updated u
|
|
LEFT JOIN provinces p ON p.id = u.province_id`
|
|
|
|
row := r.client.QueryRow(ctx, query,
|
|
name, address, dto.Region, dto.ProvinceId, dto.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
|
|
}
|
|
return item, err
|
|
}
|
|
|
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
return r.generic.Delete(ctx, id)
|
|
}
|
|
|
|
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) ([]byte, []byte, error) {
|
|
nameJSON, err := json.Marshal(name)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
addressJSON, err := json.Marshal(address)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return nameJSON, addressJSON, nil
|
|
}
|
|
|
|
func isUniqueViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
|
}
|
|
|
|
func scanBranch(row genericrepo.Scanner) (branches.BranchDTO, error) {
|
|
var item branches.BranchDTO
|
|
var nameJSON, addressJSON, provinceNameJSON []byte
|
|
var uniqueCode *string
|
|
|
|
err := row.Scan(
|
|
&item.Id, &uniqueCode, &nameJSON, &addressJSON, &item.Region, &item.ProvinceId, &provinceNameJSON,
|
|
&item.PhoneNumbers,
|
|
&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
|
|
}
|
|
}
|
|
return item, nil
|
|
}
|