added soft deleted
This commit is contained in:
50
db/migrations/20260905130000_add_soft_delete.down.sql
Normal file
50
db/migrations/20260905130000_add_soft_delete.down.sql
Normal file
@@ -0,0 +1,50 @@
|
||||
-- Reverse 20260905130000_add_soft_delete.up.sql
|
||||
|
||||
DROP INDEX IF EXISTS permission_user_permission_id_user_id_idx;
|
||||
ALTER TABLE permission_user ADD CONSTRAINT permission_user_permission_id_user_id_key UNIQUE (permission_id, user_id);
|
||||
|
||||
DROP INDEX IF EXISTS permission_role_permission_id_role_id_idx;
|
||||
ALTER TABLE permission_role ADD CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id);
|
||||
|
||||
DROP INDEX IF EXISTS currencies_from_to_idx;
|
||||
ALTER TABLE currencies ADD CONSTRAINT currencies_from_to_key UNIQUE (currency_from, currency_to);
|
||||
|
||||
DROP INDEX IF EXISTS backups_file_name_idx;
|
||||
ALTER TABLE backups ADD CONSTRAINT backups_file_name_key UNIQUE (file_name);
|
||||
|
||||
DROP INDEX IF EXISTS branches_unique_code_idx;
|
||||
ALTER TABLE branches ADD CONSTRAINT branches_unique_code_key UNIQUE (unique_code);
|
||||
|
||||
DROP INDEX IF EXISTS idx_users_phone;
|
||||
CREATE UNIQUE INDEX idx_users_phone
|
||||
ON users (phone)
|
||||
WHERE phone <> '';
|
||||
|
||||
DROP INDEX IF EXISTS idx_users_username;
|
||||
CREATE UNIQUE INDEX idx_users_username
|
||||
ON users (LOWER(username))
|
||||
WHERE username <> '';
|
||||
|
||||
ALTER TABLE currencies DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE backups DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE card_rekwizit_orders DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE visa_master_payment_orders DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE loan_paid_off_letters DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE loans DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE loan_orders DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE card_pin_orders DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE card_orders DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE cards DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE loan_order_required_docs DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE loan_types DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE card_states DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE card_types DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE branch_user DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE branches DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE provinces DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE permission_user DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE permission_role DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE role_user DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE permissions DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE roles DROP COLUMN IF EXISTS deleted_at;
|
||||
ALTER TABLE users DROP COLUMN IF EXISTS deleted_at;
|
||||
69
db/migrations/20260905130000_add_soft_delete.up.sql
Normal file
69
db/migrations/20260905130000_add_soft_delete.up.sql
Normal file
@@ -0,0 +1,69 @@
|
||||
-- Add deleted_at (soft delete) to every table that has a DELETE endpoint but
|
||||
-- doesn't already support soft delete. card_balances already has deleted_at
|
||||
-- (see 20260702125108_init.up.sql) and is left untouched. activity_logs and
|
||||
-- registration_verifications have no DELETE endpoint / aren't a user-managed
|
||||
-- CRUD resource, so they're intentionally excluded.
|
||||
|
||||
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE roles ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE permissions ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE role_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE permission_role ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE permission_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE provinces ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE branches ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE branch_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE card_types ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE card_states ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE loan_types ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE loan_order_required_docs ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE cards ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE card_orders ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE card_pin_orders ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE loan_orders ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE loans ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE loan_paid_off_letters ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE visa_master_payment_orders ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE card_rekwizit_orders ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE backups ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE currencies ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
|
||||
-- Rescope existing uniqueness constraints to active (non-soft-deleted) rows
|
||||
-- only, so a soft-deleted row's unique value (username, phone, branch code,
|
||||
-- backup file name, currency pair, permission-role/permission-user pair) can
|
||||
-- be reused by a new row.
|
||||
|
||||
DROP INDEX IF EXISTS idx_users_username;
|
||||
CREATE UNIQUE INDEX idx_users_username
|
||||
ON users (LOWER(username))
|
||||
WHERE username <> '' AND deleted_at IS NULL;
|
||||
|
||||
DROP INDEX IF EXISTS idx_users_phone;
|
||||
CREATE UNIQUE INDEX idx_users_phone
|
||||
ON users (phone)
|
||||
WHERE phone <> '' AND deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE branches DROP CONSTRAINT IF EXISTS branches_unique_code_key;
|
||||
CREATE UNIQUE INDEX branches_unique_code_idx
|
||||
ON branches (unique_code)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE backups DROP CONSTRAINT IF EXISTS backups_file_name_key;
|
||||
CREATE UNIQUE INDEX backups_file_name_idx
|
||||
ON backups (file_name)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE currencies DROP CONSTRAINT IF EXISTS currencies_from_to_key;
|
||||
CREATE UNIQUE INDEX currencies_from_to_idx
|
||||
ON currencies (currency_from, currency_to)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE permission_role DROP CONSTRAINT IF EXISTS permission_role_permission_id_role_id_key;
|
||||
CREATE UNIQUE INDEX permission_role_permission_id_role_id_idx
|
||||
ON permission_role (permission_id, role_id)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE permission_user DROP CONSTRAINT IF EXISTS permission_user_permission_id_user_id_key;
|
||||
CREATE UNIQUE INDEX permission_user_permission_id_user_id_idx
|
||||
ON permission_user (permission_id, user_id)
|
||||
WHERE deleted_at IS NULL;
|
||||
@@ -7495,9 +7495,6 @@ const docTemplate = `{
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -7564,9 +7561,6 @@ const docTemplate = `{
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -7489,9 +7489,6 @@
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -7558,9 +7555,6 @@
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -137,8 +137,6 @@ definitions:
|
||||
type: integer
|
||||
region:
|
||||
type: string
|
||||
uniqueCode:
|
||||
type: string
|
||||
required:
|
||||
- address
|
||||
- name
|
||||
@@ -183,8 +181,6 @@ definitions:
|
||||
type: integer
|
||||
region:
|
||||
type: string
|
||||
uniqueCode:
|
||||
type: string
|
||||
required:
|
||||
- address
|
||||
- name
|
||||
|
||||
@@ -77,7 +77,7 @@ func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup
|
||||
}
|
||||
|
||||
func buildListQuery(filter backup.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"b.deleted_at IS NULL"}
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, shared.LikePattern(filter.Search))
|
||||
@@ -89,9 +89,6 @@ func buildListQuery(filter backup.ListFilter) (whereClause string, args []interf
|
||||
conditions = append(conditions, fmt.Sprintf("b.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
@@ -103,7 +100,7 @@ func escapeLike(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (backup.BackupDTO, error) {
|
||||
query := `SELECT ` + backupSelectColumns + backupFromClause + ` WHERE b.id = $1`
|
||||
query := `SELECT ` + backupSelectColumns + backupFromClause + ` WHERE b.id = $1 AND b.deleted_at IS NULL`
|
||||
return scanBackupWithUser(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (car
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"co.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
@@ -157,15 +157,11 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
|
||||
conditions = append(conditions, fmt.Sprintf("co.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
|
||||
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1`
|
||||
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1 AND co.deleted_at IS NULL`
|
||||
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -207,7 +203,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -104,7 +104,7 @@ func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter)
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"cpo.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
@@ -133,15 +133,11 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
|
||||
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1`
|
||||
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1 AND cpo.deleted_at IS NULL`
|
||||
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -182,7 +178,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -117,7 +117,7 @@ func (r *repository) List(ctx context.Context, filter cardrekwizit.ListFilter) (
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardrekwizit.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"cro.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
@@ -146,15 +146,11 @@ func buildListQuery(filter cardrekwizit.ListFilter) (whereClause string, args []
|
||||
conditions = append(conditions, fmt.Sprintf("cro.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
query := `SELECT ` + cardRekwizitOrderSelectColumns + cardRekwizitOrderFromClause + ` WHERE cro.id = $1`
|
||||
query := `SELECT ` + cardRekwizitOrderSelectColumns + cardRekwizitOrderFromClause + ` WHERE cro.id = $1 AND cro.deleted_at IS NULL`
|
||||
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -195,7 +191,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardrekwizit.Upda
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_rekwizit_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -97,7 +97,7 @@ func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.L
|
||||
}
|
||||
|
||||
func buildListQuery(filter cards.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"c.deleted_at IS NULL"}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
@@ -114,15 +114,11 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
|
||||
conditions = append(conditions, fmt.Sprintf("c.type = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
|
||||
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1`
|
||||
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
|
||||
return scanCardWithUser(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -162,7 +158,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -100,7 +100,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET
|
||||
price = $1, name = $2, notes = $3, active = $4
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||
@@ -113,7 +113,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET active = $1
|
||||
WHERE id = $2
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
||||
|
||||
@@ -95,7 +95,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
||||
UPDATE card_states SET
|
||||
price = $1, name = $2, notes = $3, active = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING %s`, reasonReturningColumns)
|
||||
|
||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||
|
||||
@@ -135,7 +135,7 @@ func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (vi
|
||||
}
|
||||
|
||||
func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"o.deleted_at IS NULL"}
|
||||
|
||||
if filter.Name != "" {
|
||||
args = append(args, shared.LikePattern(filter.Name))
|
||||
@@ -168,15 +168,11 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
|
||||
conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1`
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1 AND o.deleted_at IS NULL`
|
||||
return scanOrder(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -217,7 +213,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto visamaster.Update
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -84,7 +84,7 @@ func (r *repository) List(ctx context.Context, filter currency.ListFilter) (curr
|
||||
}
|
||||
|
||||
func buildListQuery(filter currency.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"c.deleted_at IS NULL"}
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, shared.LikePattern(filter.Search))
|
||||
@@ -104,14 +104,11 @@ func buildListQuery(filter currency.ListFilter) (whereClause string, args []inte
|
||||
conditions = append(conditions, fmt.Sprintf("c.currency_to = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", 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`
|
||||
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
|
||||
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -139,7 +136,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCu
|
||||
currency_from = $1, currency_to = $2, value = $3::numeric,
|
||||
updated_by = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING ` + currencyColumnsSQL + `
|
||||
)
|
||||
SELECT ` + currencySelectColumns + `
|
||||
|
||||
@@ -137,7 +137,7 @@ func (r *repository) loanOrdersMetric(ctx context.Context, branchIds []int64, wi
|
||||
extra = append(extra, branchIds)
|
||||
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM loan_orders WHERE true` + where)
|
||||
query := metricSQL(`FROM loan_orders WHERE deleted_at IS NULL` + where)
|
||||
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
|
||||
}
|
||||
|
||||
@@ -146,9 +146,9 @@ func (r *repository) activeCardsMetric(ctx context.Context, branchIds []int64, w
|
||||
var extra []interface{}
|
||||
if len(branchIds) > 0 {
|
||||
extra = append(extra, branchIds)
|
||||
where = fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = c.user_id AND bu.branch_id = ANY($%d))", len(extra)+4)
|
||||
where = fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = c.user_id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM cards c WHERE true` + where)
|
||||
query := metricSQL(`FROM cards c WHERE c.deleted_at IS NULL` + where)
|
||||
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
|
||||
}
|
||||
|
||||
@@ -157,9 +157,9 @@ func (r *repository) activeCustomersMetric(ctx context.Context, branchIds []int6
|
||||
var extra []interface{}
|
||||
if len(branchIds) > 0 {
|
||||
extra = append(extra, branchIds)
|
||||
where += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d))", len(extra)+4)
|
||||
where += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM users u WHERE true` + where)
|
||||
query := metricSQL(`FROM users u WHERE u.deleted_at IS NULL` + where)
|
||||
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ func (r *repository) onlinePaymentsMetric(ctx context.Context, branchIds []int64
|
||||
extra = append(extra, branchIds)
|
||||
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM visa_master_payment_orders WHERE true` + where)
|
||||
query := metricSQL(`FROM visa_master_payment_orders WHERE deleted_at IS NULL` + where)
|
||||
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ func (r *repository) monthlyCounts(ctx context.Context, table string, branchIds
|
||||
query := fmt.Sprintf(`
|
||||
SELECT EXTRACT(MONTH FROM created_at)::int, COUNT(*)
|
||||
FROM %s
|
||||
WHERE EXTRACT(YEAR FROM created_at) = $1%s
|
||||
WHERE EXTRACT(YEAR FROM created_at) = $1 AND deleted_at IS NULL%s
|
||||
GROUP BY 1`, table, where)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
@@ -270,7 +270,7 @@ func (r *repository) dailyCounts(ctx context.Context, table string, branchIds []
|
||||
query := fmt.Sprintf(`
|
||||
SELECT created_at::date, COUNT(*)
|
||||
FROM %s
|
||||
WHERE created_at >= $1%s
|
||||
WHERE created_at >= $1 AND deleted_at IS NULL%s
|
||||
GROUP BY 1`, table, where)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
@@ -321,7 +321,7 @@ func (r *repository) loanStatusBreakdown(ctx context.Context, branchIds []int64)
|
||||
query := fmt.Sprintf(`
|
||||
SELECT %s, COUNT(*)
|
||||
FROM loan_orders
|
||||
WHERE true%s
|
||||
WHERE deleted_at IS NULL%s
|
||||
GROUP BY 1`, loanStatusBucketSQL, where)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
@@ -369,7 +369,7 @@ func (r *repository) recentActivity(ctx context.Context, branchIds []int64, limi
|
||||
query := fmt.Sprintf(`
|
||||
SELECT id, unique_id, customer_name, customer_surname, loan_amount, status, created_at
|
||||
FROM loan_orders
|
||||
WHERE true%s
|
||||
WHERE deleted_at IS NULL%s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $%d`, where, len(args))
|
||||
|
||||
|
||||
@@ -32,26 +32,28 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
|
||||
const (
|
||||
loginByNameQuery = `
|
||||
SELECT id, password FROM users
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
OR LOWER(TRIM(username)) = LOWER(TRIM($1))
|
||||
WHERE (LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
OR LOWER(TRIM(username)) = LOWER(TRIM($1)))
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
loginByPhoneQuery = `
|
||||
SELECT id, password FROM users
|
||||
WHERE phone = $1
|
||||
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
|
||||
WHERE (phone = $1
|
||||
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2))
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1 AND deleted_at IS NULL`
|
||||
)
|
||||
|
||||
const profileFromClause = ` FROM users u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
WHERE ru.user_id = u.id AND ru.deleted_at IS NULL
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
LEFT JOIN roles r ON r.id = ru.role_id AND r.deleted_at IS NULL`
|
||||
|
||||
const profileBranchesJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
@@ -63,7 +65,7 @@ const profileBranchesJSON = `COALESCE((
|
||||
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = u.id
|
||||
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::json)`
|
||||
@@ -77,24 +79,25 @@ const profilePermissionsJSON = `COALESCE((
|
||||
'module', COALESCE(p.module, '')
|
||||
) ORDER BY p.module, p.id)
|
||||
FROM permissions p
|
||||
WHERE NOT EXISTS (
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny'
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
||||
)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow'
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM permission_role pr
|
||||
WHERE pr.role_id = r.id AND pr.permission_id = p.id
|
||||
WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL
|
||||
)
|
||||
)
|
||||
), '[]'::json)`
|
||||
|
||||
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
|
||||
r.id, r.code, r.name, r.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
|
||||
r.id, r.code, r.name, r.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL`
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
||||
phone := strings.TrimSpace(dto.Phone)
|
||||
@@ -127,7 +130,7 @@ const updateProfileQuery = `
|
||||
UPDATE users SET
|
||||
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6`
|
||||
WHERE id = $6 AND deleted_at IS NULL`
|
||||
|
||||
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
|
||||
tag, err := r.client.Exec(ctx, updateProfileQuery,
|
||||
@@ -198,8 +201,9 @@ func (r *repository) UserExists(ctx context.Context, username, phone string) (bo
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE LOWER(username) = LOWER($1)
|
||||
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2
|
||||
WHERE (LOWER(username) = LOWER($1)
|
||||
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2)
|
||||
AND deleted_at IS NULL
|
||||
)`
|
||||
var exists bool
|
||||
err := r.client.QueryRow(ctx, query, username, digitString(phone)).Scan(&exists)
|
||||
@@ -302,7 +306,7 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
|
||||
func (r *repository) GetUserByName(ctx context.Context, name string) (auth.UserIdentity, error) {
|
||||
const query = `
|
||||
SELECT id, name, username, phone FROM users
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1)) AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
|
||||
var user auth.UserIdentity
|
||||
@@ -324,7 +328,7 @@ func (r *repository) CompletePasswordReset(ctx context.Context, userID int, veri
|
||||
UPDATE users SET
|
||||
password = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2`, passwordHash, userID)
|
||||
WHERE id = $2 AND deleted_at IS NULL`, passwordHash, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto permission.Update
|
||||
UPDATE permissions SET
|
||||
code = $1, name = $2, guard_name = $3, module = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module, id))
|
||||
|
||||
@@ -26,7 +26,7 @@ func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermis
|
||||
WITH upserted AS (
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (permission_id, role_id) DO UPDATE SET
|
||||
ON CONFLICT (permission_id, role_id) WHERE deleted_at IS NULL DO UPDATE SET
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
RETURNING id, permission_id, role_id, created_at, updated_at
|
||||
)
|
||||
|
||||
@@ -26,7 +26,7 @@ func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermis
|
||||
WITH upserted AS (
|
||||
INSERT INTO permission_user (permission_id, user_id, effect)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (permission_id, user_id) DO UPDATE SET
|
||||
ON CONFLICT (permission_id, user_id) WHERE deleted_at IS NULL DO UPDATE SET
|
||||
effect = EXCLUDED.effect,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
RETURNING id, permission_id, user_id, effect, created_at, updated_at
|
||||
|
||||
@@ -178,14 +178,14 @@ func AppendBranchIDs(conditions []string, args []interface{}, column string, ids
|
||||
|
||||
func UserInBranchSQL(userExpr string, placeholder int) string {
|
||||
return fmt.Sprintf(`(
|
||||
EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = %s AND bu.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d))
|
||||
OR EXISTS (SELECT 1 FROM card_balances cb WHERE cb.created_by = %s AND cb.branch_id = ANY($%d))
|
||||
EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = %s AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d) AND co.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d) AND lo.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d) AND cpo.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d) AND cro.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d) AND vmo.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d) AND lpl.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM card_balances cb WHERE cb.created_by = %s AND cb.branch_id = ANY($%d) AND cb.deleted_at IS NULL)
|
||||
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,19 +36,19 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny'
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
||||
) THEN false
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow'
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
||||
) THEN true
|
||||
ELSE EXISTS (
|
||||
SELECT 1
|
||||
FROM role_user ru
|
||||
JOIN permission_role pr ON pr.role_id = ru.role_id
|
||||
JOIN permissions p ON p.id = pr.permission_id
|
||||
WHERE ru.user_id = $1 AND p.code = $2
|
||||
WHERE ru.user_id = $1 AND p.code = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL
|
||||
)
|
||||
END`
|
||||
|
||||
@@ -64,7 +64,7 @@ func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string,
|
||||
SELECT r.code, r.guard_name
|
||||
FROM role_user ru
|
||||
JOIN roles r ON r.id = ru.role_id
|
||||
WHERE ru.user_id = $1
|
||||
WHERE ru.user_id = $1 AND ru.deleted_at IS NULL AND r.deleted_at IS NULL
|
||||
ORDER BY ru.id
|
||||
LIMIT 1`
|
||||
|
||||
@@ -80,7 +80,8 @@ func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error)
|
||||
const query = `
|
||||
SELECT bu.branch_id
|
||||
FROM branch_user bu
|
||||
WHERE bu.user_id = $1
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = $1 AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
|
||||
ORDER BY bu.id`
|
||||
|
||||
rows, err := s.client.Query(ctx, query, userID)
|
||||
@@ -104,7 +105,7 @@ func (s *Service) UserVisibleInBranches(ctx context.Context, userID int64, branc
|
||||
if len(branchIDs) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
query := `SELECT ` + UserInBranchSQL("u.id", 2) + ` FROM users u WHERE u.id = $1`
|
||||
query := `SELECT ` + UserInBranchSQL("u.id", 2) + ` FROM users u WHERE u.id = $1 AND u.deleted_at IS NULL`
|
||||
var ok bool
|
||||
err := s.client.QueryRow(ctx, query, userID, branchIDs).Scan(&ok)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
|
||||
@@ -77,7 +77,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDT
|
||||
UPDATE roles SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
WHERE id = $4 AND deleted_at IS NULL
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
|
||||
@@ -24,7 +24,7 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.R
|
||||
func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) {
|
||||
query := `
|
||||
WITH existing AS (
|
||||
SELECT id FROM role_user WHERE user_id = $2 ORDER BY id LIMIT 1
|
||||
SELECT id FROM role_user WHERE user_id = $2 AND deleted_at IS NULL ORDER BY id LIMIT 1
|
||||
), updated AS (
|
||||
UPDATE role_user SET
|
||||
role_id = $1,
|
||||
|
||||
@@ -52,7 +52,7 @@ const userBranchesJSON = `COALESCE((
|
||||
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = u.id
|
||||
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::json)`
|
||||
@@ -66,18 +66,19 @@ const userPermissionsJSON = `COALESCE((
|
||||
'module', COALESCE(p.module, '')
|
||||
) ORDER BY p.module, p.id)
|
||||
FROM permissions p
|
||||
WHERE NOT EXISTS (
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny'
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
||||
)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow'
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM permission_role pr
|
||||
WHERE pr.role_id = r.id AND pr.permission_id = p.id
|
||||
WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL
|
||||
)
|
||||
)
|
||||
), '[]'::json)`
|
||||
@@ -126,12 +127,12 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use
|
||||
}
|
||||
|
||||
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"u.deleted_at IS NULL"}
|
||||
if len(filter.BranchIds) > 0 {
|
||||
args = append(args, filter.BranchIds)
|
||||
conditions = append(conditions, fmt.Sprintf(`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d))`, len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf(`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)`, len(args)))
|
||||
} else {
|
||||
conditions = append(conditions, `EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`)
|
||||
conditions = append(conditions, `EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.deleted_at IS NULL)`)
|
||||
}
|
||||
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
@@ -177,7 +178,7 @@ var listVisibleRoles = []string{"user"}
|
||||
func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = userFromClause
|
||||
|
||||
var conditions []string
|
||||
conditions := []string{"u.deleted_at IS NULL"}
|
||||
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
||||
if len(roles) > 0 {
|
||||
placeholders := make([]string, len(roles))
|
||||
@@ -197,10 +198,6 @@ func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause
|
||||
conditions = append(conditions, rbac.UserInBranchSQL("u.id", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
@@ -220,18 +217,13 @@ func appendNameSearch(conditions []string, args []interface{}, term string) ([]s
|
||||
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
|
||||
if len(filter.BranchIds) == 0 {
|
||||
excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`
|
||||
if whereClause == "" {
|
||||
whereClause = " WHERE " + excludeStaff
|
||||
} else {
|
||||
whereClause += " AND " + excludeStaff
|
||||
}
|
||||
whereClause += ` AND NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.deleted_at IS NULL)`
|
||||
}
|
||||
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s, %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userPermissionsJSON, userFromClause)
|
||||
query := fmt.Sprintf(`SELECT %s, %s, %s%s WHERE u.id = $1 AND u.deleted_at IS NULL`, userColumns, userBranchesJSON, userPermissionsJSON, userFromClause)
|
||||
item, err := scanUserDetail(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user.UserDTO{}, err
|
||||
@@ -301,7 +293,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDT
|
||||
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
|
||||
role = $8, active = $9,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $10
|
||||
WHERE id = $10 AND deleted_at IS NULL
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
item, err := scanUser(tx.QueryRow(ctx, query,
|
||||
@@ -352,7 +344,7 @@ func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode str
|
||||
}
|
||||
|
||||
func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM role_user WHERE user_id = $1`, userID); err != nil {
|
||||
if _, err := tx.Exec(ctx, `UPDATE role_user SET deleted_at = now() WHERE user_id = $1 AND deleted_at IS NULL`, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
return assignRoleByCode(ctx, tx, userID, roleCode)
|
||||
|
||||
@@ -25,7 +25,7 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.
|
||||
func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) {
|
||||
query := `
|
||||
WITH existing AS (
|
||||
SELECT id FROM branch_user WHERE user_id = $2 ORDER BY id LIMIT 1
|
||||
SELECT id FROM branch_user WHERE user_id = $2 AND deleted_at IS NULL ORDER BY id LIMIT 1
|
||||
), updated AS (
|
||||
UPDATE branch_user SET
|
||||
branch_id = $1,
|
||||
@@ -57,7 +57,7 @@ func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBran
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
JOIN users u ON u.id = bu.user_id
|
||||
WHERE bu.id = $1`
|
||||
WHERE bu.id = $1 AND bu.deleted_at IS NULL`
|
||||
return scanUserBranch(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ func resolveSource(source string) string {
|
||||
|
||||
func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
@@ -95,7 +95,7 @@ func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
|
||||
|
||||
func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
@@ -150,7 +150,7 @@ func (r *repository) List(ctx context.Context, filter loanorders.ListFilter) (lo
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"lo.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
@@ -179,33 +179,42 @@ func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []in
|
||||
conditions = append(conditions, fmt.Sprintf("lo.source = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) {
|
||||
query := `SELECT ` + loanOrderSelectColumns + loanOrderFromClause + ` WHERE lo.id = $1`
|
||||
query := `SELECT ` + loanOrderSelectColumns + loanOrderFromClause + ` WHERE lo.id = $1 AND lo.deleted_at IS NULL`
|
||||
return scanLoanOrder(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
// nextUniqueIDSQL computes unique_id as the last numeric value stored in
|
||||
// loan_orders plus one, zero-padded to 4 digits. Non-numeric rows (e.g. legacy
|
||||
// "LO-2026-0001") are ignored so CREATE does not fail with a cast error.
|
||||
const nextUniqueIDSQL = `(SELECT LPAD((COALESCE(MAX(CASE WHEN unique_id ~ '^[0-9]+$' THEN unique_id::bigint END), 0) + 1)::text, 4, '0') FROM loan_orders)`
|
||||
// nextUniqueIDExprTemplate builds unique_id as "TB" + the referenced branch's
|
||||
// unique_code + "-" + the last numeric suffix stored in loan_orders plus one,
|
||||
// zero-padded to 4 digits, e.g. "TB1303-8027". substring(... from '([0-9]+)$')
|
||||
// pulls the trailing digit run regardless of prefix, so both legacy plain rows
|
||||
// ("0008") and new "TB<code>-NNNN" rows are accounted for when computing the
|
||||
// next value. The single %s is filled in with the placeholder bound to the
|
||||
// target branch id.
|
||||
const nextUniqueIDExprTemplate = `(
|
||||
SELECT 'TB' || COALESCE((SELECT unique_code FROM branches WHERE id = %s), '') || '-' ||
|
||||
LPAD((SELECT COALESCE(MAX(substring(unique_id from '([0-9]+)$')::bigint), 0) + 1 FROM loan_orders)::text, 4, '0')
|
||||
)`
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
// unique_id is supplied positionally via nextUniqueIDSQL below, so drop it
|
||||
// from the bound args to avoid double-supplying the first column.
|
||||
args := createArgs(dto)[1:]
|
||||
// unique_id is supplied positionally via nextUniqueIDExpr below, so it's not
|
||||
// part of createArgs; the target branch id is bound a second time (as its
|
||||
// own dedicated trailing placeholder) so that subquery doesn't need to guess
|
||||
// which $N slot branch_id already occupies among the other bound columns.
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
branchIDPlaceholder := fmt.Sprintf("$%d", len(args)+1)
|
||||
args = append(args, dto.BranchId.Int64())
|
||||
nextUniqueIDExpr := fmt.Sprintf(nextUniqueIDExprTemplate, branchIDPlaceholder)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO loan_orders (%s) VALUES (%s, %s)
|
||||
@@ -218,7 +227,7 @@ func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderD
|
||||
LEFT JOIN users u ON u.id = lo.user_id
|
||||
LEFT JOIN provinces p ON p.id = lo.work_province_id
|
||||
LEFT JOIN loan_order_required_docs d ON d.id = lo.loan_order_required_doc_id`,
|
||||
loanOrderWritableColumnsSQL, nextUniqueIDSQL, strings.Join(placeholders, ", "),
|
||||
loanOrderWritableColumnsSQL, nextUniqueIDExpr, strings.Join(placeholders, ", "),
|
||||
loanOrderColumnsSQL, loanOrderSelectColumns,
|
||||
)
|
||||
|
||||
@@ -228,8 +237,12 @@ func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderD
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loanorders.UpdateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(loanOrderWritableColumns))
|
||||
for i, column := range loanOrderWritableColumns {
|
||||
// unique_id is assigned once at creation and never touched again, so it's
|
||||
// excluded here (index 0 of loanOrderWritableColumns) — including it would
|
||||
// overwrite the assigned reference number with NULL on every update.
|
||||
writableColumns := loanOrderWritableColumns[1:]
|
||||
assignments := make([]string, len(writableColumns))
|
||||
for i, column := range writableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
@@ -237,7 +250,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanorders.Update
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE loan_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -87,7 +87,6 @@ type LoanOrderDTO struct {
|
||||
type CreateLoanOrderDTO struct {
|
||||
Source string `json:"source"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
LoanType shared.FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
|
||||
@@ -155,7 +154,6 @@ type CreateLoanOrderDTO struct {
|
||||
}
|
||||
|
||||
type UpdateLoanOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Source string `json:"source"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
LoanType shared.FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"`
|
||||
|
||||
@@ -108,7 +108,7 @@ func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter)
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"l.deleted_at IS NULL"}
|
||||
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, shared.LikePattern(filter.PassportId))
|
||||
@@ -145,16 +145,12 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args
|
||||
conditions = append(conditions, fmt.Sprintf("l.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (loanpaidletter.ListBranchesByProvinceDTO, error) {
|
||||
args := []interface{}{provinceID}
|
||||
where := ` WHERE province_id = $1`
|
||||
where := ` WHERE province_id = $1 AND deleted_at IS NULL`
|
||||
if activeOnly {
|
||||
where += ` AND active = true`
|
||||
}
|
||||
@@ -193,7 +189,7 @@ func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int6
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
query := `SELECT ` + letterSelectColumns + letterFromClause + ` WHERE l.id = $1`
|
||||
query := `SELECT ` + letterSelectColumns + letterFromClause + ` WHERE l.id = $1 AND l.deleted_at IS NULL`
|
||||
return scanLoanPaidLetter(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -234,7 +230,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.Up
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE loan_paid_off_letters SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -88,7 +88,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.Upd
|
||||
UPDATE loan_order_required_docs SET
|
||||
name = $1, value = $2, active = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
WHERE id = $4 AND deleted_at IS NULL
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, dto.Name, dto.Value, dto.Active, id))
|
||||
@@ -103,7 +103,7 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (l
|
||||
UPDATE loan_order_required_docs SET
|
||||
active = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, active, id))
|
||||
|
||||
@@ -75,7 +75,7 @@ func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter)
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"l.deleted_at IS NULL"}
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, shared.LikePattern(filter.PassportId))
|
||||
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args)))
|
||||
@@ -91,15 +91,11 @@ func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args
|
||||
conditions = append(conditions, rbac.UserInBranchSQL("l.user_id", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
query := `SELECT ` + loanColumns + loanFromClause + ` WHERE l.id = $1`
|
||||
query := `SELECT ` + loanColumns + loanFromClause + ` WHERE l.id = $1 AND l.deleted_at IS NULL`
|
||||
return scanLoanRepayment(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -123,7 +119,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.Up
|
||||
UPDATE loans SET
|
||||
user_id = $1, passport_serie = $2, passport_id = $3, account_number = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING ` + loanReturningColumns + `
|
||||
)
|
||||
SELECT ` + loanColumns + `
|
||||
|
||||
@@ -95,7 +95,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLo
|
||||
UPDATE loan_types SET
|
||||
name = $1, tax = $2, maturity = $3, notes = $4, active = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
WHERE id = $6 AND deleted_at IS NULL
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
item, err := scanLoanType(r.client.QueryRow(ctx, query, name, dto.Tax, dto.LoanTerm, notes, dto.Active, id))
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -173,7 +173,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE provinces SET name = $1, region = $2, active = $3 WHERE id = $4 RETURNING `+provinceSelectColumns,
|
||||
`UPDATE provinces SET name = $1, region = $2, active = $3 WHERE id = $4 AND deleted_at IS NULL RETURNING `+provinceSelectColumns,
|
||||
name, region, dto.Active, id,
|
||||
)
|
||||
item, err := scanProvince(row)
|
||||
|
||||
@@ -31,7 +31,7 @@ func New[T any](client postgresql.Client, table, columns string, scan func(Scann
|
||||
}
|
||||
|
||||
func (r *Repository[T]) GetByID(ctx context.Context, id int64) (T, error) {
|
||||
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1`, id)
|
||||
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1 AND deleted_at IS NULL`, id)
|
||||
item, err := r.scan(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
var zero T
|
||||
@@ -44,11 +44,13 @@ func (r *Repository[T]) Delete(ctx context.Context, id int64) error {
|
||||
return Delete(ctx, r.client, r.table, id)
|
||||
}
|
||||
|
||||
// Delete runs the hard-delete-by-id pattern shared by every module that
|
||||
// Delete runs the soft-delete-by-id pattern shared by every module that
|
||||
// doesn't need the full Repository[T] (e.g. association tables, or entities
|
||||
// whose List/GetByID require joins genericrepo doesn't model).
|
||||
// whose List/GetByID require joins genericrepo doesn't model). Rows are never
|
||||
// hard-deleted so foreign keys pointing at them never break, and deletes are
|
||||
// recoverable.
|
||||
func Delete(ctx context.Context, client postgresql.Client, table string, id int64) error {
|
||||
tag, err := client.Exec(ctx, `DELETE FROM `+table+` WHERE id = $1`, id)
|
||||
tag, err := client.Exec(ctx, `UPDATE `+table+` SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,6 +60,15 @@ func Delete(ctx context.Context, client postgresql.Client, table string, id int6
|
||||
return nil
|
||||
}
|
||||
|
||||
// withDeletedAtFilter folds a mandatory "deleted_at IS NULL" condition into a
|
||||
// caller-supplied where clause (empty or starting with " WHERE ", see List).
|
||||
func withDeletedAtFilter(where string) string {
|
||||
if where == "" {
|
||||
return " WHERE deleted_at IS NULL"
|
||||
}
|
||||
return where + " AND deleted_at IS NULL"
|
||||
}
|
||||
|
||||
// List runs a paginated query. where must be empty or start with " WHERE "
|
||||
// (see province's buildListQuery for the convention); args are the
|
||||
// positional parameters referenced by where, in order. orderBy is the raw
|
||||
@@ -66,6 +77,7 @@ func (r *Repository[T]) List(ctx context.Context, where string, args []interface
|
||||
if orderBy == "" {
|
||||
orderBy = "id"
|
||||
}
|
||||
where = withDeletedAtFilter(where)
|
||||
|
||||
var count int64
|
||||
countQuery := `SELECT COUNT(*) FROM ` + r.table + where
|
||||
|
||||
Reference in New Issue
Block a user