added soft deleted
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

This commit is contained in:
guwandyk committed 2026-09-05 17:58:23 +05:00
1 parent d1a6fcaadc
commit e0d03730de
36 files changed
+327 -217

No files matched your search

+52 -33
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"strings"
"online-back/internal/identity/rbac"
@@ -18,6 +19,29 @@ import (
"github.com/jackc/pgx/v4"
)
// regionUniqueCodePrefix maps a branch's region code to the 2-digit prefix
// used when generating its unique_code. The suffix is 2 random digits, so
// each region can hold at most 100 branches before generateUniqueCode's
// retry budget is exhausted.
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
}
const maxUniqueCodeAttempts = 20
func generateUniqueCode(region string) (string, error) {
prefix, ok := regionUniqueCodePrefix[region]
if !ok {
return "", fmt.Errorf("unsupported region")
}
return prefix + fmt.Sprintf("%02d", rand.Intn(100)), nil
}
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[branches.BranchDTO]
@@ -98,7 +122,7 @@ func (r *repository) List(ctx context.Context, filter branches.ListFilter) (bran
}
func buildListQuery(filter branches.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
conditions := []string{"b.deleted_at IS NULL"}
if filter.ProvinceID != nil {
args = append(args, *filter.ProvinceID)
@@ -131,15 +155,11 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
conditions, args = rbac.AppendBranchIDs(conditions, args, "b.id", filter.BranchIds)
}
if len(conditions) == 0 {
return "", args
}
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`, branchSelectColumns, branchFromClause)
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) {
@@ -177,17 +197,26 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
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, 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")
for attempt := 0; attempt < maxUniqueCodeAttempts; attempt++ {
code, err := generateUniqueCode(dto.Region)
if err != nil {
return branches.BranchDTO{}, err
}
row := r.client.QueryRow(ctx, query,
code, 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) {
continue
}
return item, err
}
return item, err
return branches.BranchDTO{}, fmt.Errorf("could not generate a unique branch code, try again")
}
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
@@ -203,12 +232,12 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
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
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 + `
@@ -216,7 +245,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
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, dto.PhoneNumbers,
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,
@@ -225,9 +254,6 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
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
}
@@ -261,13 +287,6 @@ func marshalBranchJSON(name, address branches.LocalizedText) ([]byte, []byte, er
return nameJSON, addressJSON, 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"
-2
View File
@@ -27,7 +27,6 @@ type BranchDTO struct {
}
type CreateBranchDTO struct {
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name" binding:"required"`
Address LocalizedText `json:"address" binding:"required"`
Region string `json:"region" binding:"required"`
@@ -45,7 +44,6 @@ type CreateBranchDTO struct {
}
type UpdateBranchDTO struct {
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name" binding:"required"`
Address LocalizedText `json:"address" binding:"required"`
Region string `json:"region" binding:"required"`
+6 -2
View File
@@ -290,8 +290,12 @@ func (h *handler) delete(c *gin.Context) {
}
func isClientError(err error) bool {
msg := err.Error()
return msg == "province not found" || msg == "unique code already exists"
switch err.Error() {
case "province not found", "unsupported region", "could not generate a unique branch code, try again":
return true
default:
return false
}
}
func parseActiveOnly(c *gin.Context, defaultValue bool) (bool, bool) {