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

+22 -18
View File
@@ -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
+8 -8
View File
@@ -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)
}
+7 -6
View File
@@ -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) {
+1 -1
View File
@@ -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))
+1 -1
View File
@@ -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,
+14 -22
View File
@@ -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))
}