package db import ( "context" "database/sql" "encoding/json" "errors" "fmt" "strings" "online-back/internal/identity/rbac" "online-back/internal/identity/user" "online-back/internal/shared" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" "golang.org/x/crypto/bcrypt" ) type repository struct { client postgresql.Client logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) user.Repository { return &repository{client: client, logger: logger} } const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.active, u.created_at, u.updated_at, r.id, r.code` const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at` const userFromClause = ` FROM users u LEFT JOIN LATERAL ( SELECT ru.role_id FROM role_user ru WHERE ru.user_id = u.id ORDER BY ru.id LIMIT 1 ) ru ON true LEFT JOIN roles r ON r.id = ru.role_id ` const userBranchesJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( 'id', b.id, 'uniqueCode', b.unique_code, 'name', b.name ) ORDER BY b.id) FROM ( 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 AND bu.deleted_at IS NULL AND b.deleted_at IS NULL ORDER BY b.id ) b ), '[]'::json)` const userPermissionsJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( 'id', p.id, 'code', COALESCE(p.code, ''), 'name', p.name, 'guardName', p.guard_name, 'module', COALESCE(p.module, '') ) ORDER BY p.module, p.id) FROM permissions p WHERE p.deleted_at IS NULL AND EXISTS ( SELECT 1 FROM permission_role pr WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL ) ), '[]'::json)` func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) { roles := listVisibleRoles if filter.AllRoles { roles = nil } fromClause, whereClause, args := buildFilteredListQuery(filter, roles...) return r.paginateUsers(ctx, filter, fromClause, whereClause, args) } func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) { whereClause, args := buildStaffWhere(filter) var count int64 countQuery := `SELECT COUNT(*)` + userFromClause + whereClause if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { return user.ListUserDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 listQuery := fmt.Sprintf( `SELECT %s, %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`, userColumns, userBranchesJSON, userFromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) if err != nil { return user.ListUserDTO{}, err } defer rows.Close() var items []user.UserDTO for rows.Next() { item, err := scanStaffUser(rows) if err != nil { return user.ListUserDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return user.ListUserDTO{}, err } return user.ListUserDTO{Count: count, Users: items}, nil } func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) { 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) 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 AND bu.deleted_at IS NULL)`) } conditions, args = appendNameSearch(conditions, args, filter.Search) return " WHERE " + strings.Join(conditions, " AND "), args } func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter, fromClause, whereClause string, args []interface{}) (user.ListUserDTO, error) { var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { return user.ListUserDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 listQuery := fmt.Sprintf( `SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`, userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) if err != nil { return user.ListUserDTO{}, err } defer rows.Close() var items []user.UserDTO for rows.Next() { item, err := scanUserWithRoleID(rows) if err != nil { return user.ListUserDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return user.ListUserDTO{}, err } return user.ListUserDTO{Count: count, Users: items}, nil } var listVisibleRoles = []string{"user"} func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) { fromClause = userFromClause conditions := []string{"u.deleted_at IS NULL"} conditions, args = appendNameSearch(conditions, args, filter.Search) if len(roles) > 0 { placeholders := make([]string, len(roles)) for i, role := range roles { args = append(args, role) placeholders[i] = fmt.Sprintf("$%d", len(args)) } if len(roles) == 1 { conditions = append(conditions, fmt.Sprintf(`r.code = %s`, placeholders[0])) } else { conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", "))) } } if len(filter.BranchIds) > 0 { args = append(args, filter.BranchIds) conditions = append(conditions, rbac.UserInBranchSQL("u.id", len(args))) } return fromClause, " WHERE " + strings.Join(conditions, " AND "), args } func appendNameSearch(conditions []string, args []interface{}, term string) ([]string, []interface{}) { if term == "" { return conditions, args } args = append(args, shared.LikePattern(term)) n := len(args) conditions = append(conditions, fmt.Sprintf( `(u.username ILIKE $%d OR u.first_name ILIKE $%d OR u.last_name ILIKE $%d OR CONCAT_WS(' ', u.first_name, u.last_name) ILIKE $%d)`, n, n, n, n, )) return conditions, args } 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 { 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 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 } return item, err } func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.UserDTO, error) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost) if err != nil { return user.UserDTO{}, err } active := true if dto.Active != nil { active = *dto.Active } role := strings.TrimSpace(dto.Role) if role == "" { role = "user" } tx, err := r.client.Begin(ctx) if err != nil { return user.UserDTO{}, err } defer tx.Rollback(ctx) query := fmt.Sprintf(` INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role, active) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING %s`, userReturningColumns) item, err := scanUser(tx.QueryRow(ctx, query, dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, active, )) if err != nil { return user.UserDTO{}, err } if err := assignRoleByCode(ctx, tx, item.Id, role); err != nil { return user.UserDTO{}, err } item.RoleId = roleIDByCode(ctx, tx, role) if err := tx.Commit(ctx); err != nil { return user.UserDTO{}, err } return item, nil } func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) { role := strings.TrimSpace(dto.Role) if role == "" { role = "user" } tx, err := r.client.Begin(ctx) if err != nil { return user.UserDTO{}, err } defer tx.Rollback(ctx) query := fmt.Sprintf(` UPDATE users SET 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 AND deleted_at IS NULL RETURNING %s`, userReturningColumns) item, err := scanUser(tx.QueryRow(ctx, query, dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, dto.Active, id, )) if errors.Is(err, pgx.ErrNoRows) { return user.UserDTO{}, err } if err != nil { return user.UserDTO{}, err } if err := replaceRoleByCode(ctx, tx, item.Id, role); err != nil { return user.UserDTO{}, err } item.RoleId = roleIDByCode(ctx, tx, role) if err := tx.Commit(ctx); err != nil { return user.UserDTO{}, err } return item, nil } func (r *repository) Delete(ctx context.Context, id int64) error { return genericrepo.Delete(ctx, r.client, "users", id) } func (r *repository) RoleGuardName(ctx context.Context, code string) (string, error) { var guardName string err := r.client.QueryRow(ctx, `SELECT guard_name FROM roles WHERE code = $1`, code).Scan(&guardName) if errors.Is(err, pgx.ErrNoRows) { return "", nil } return guardName, err } func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error { tag, err := tx.Exec(ctx, ` INSERT INTO role_user (role_id, user_id) SELECT r.id, $1 FROM roles r WHERE r.code = $2`, userID, roleCode) if err != nil { return err } if tag.RowsAffected() == 0 { return fmt.Errorf("role %q not found", roleCode) } return nil } func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error { 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) } func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 { var id int64 if err := tx.QueryRow(ctx, `SELECT id FROM roles WHERE code = $1`, roleCode).Scan(&id); err != nil { return nil } return &id } func scanUser(row genericrepo.Scanner) (user.UserDTO, error) { var item user.UserDTO if err := row.Scan( &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, ); err != nil { return user.UserDTO{}, err } return item, nil } func scanUserWithRoleID(row genericrepo.Scanner) (user.UserDTO, error) { var item user.UserDTO var roleID sql.NullInt64 var roleCode sql.NullString if err := row.Scan( &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, &item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, ); err != nil { return user.UserDTO{}, err } applyJoinedRole(&item, roleID, roleCode) return item, nil } func scanStaffUser(row genericrepo.Scanner) (user.UserDTO, error) { var item user.UserDTO var roleID sql.NullInt64 var roleCode sql.NullString var branchesJSON []byte if err := row.Scan( &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, &item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON, ); err != nil { return user.UserDTO{}, err } applyJoinedRole(&item, roleID, roleCode) if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil { return user.UserDTO{}, err } if item.Branches == nil { item.Branches = []user.StaffBranchDTO{} } return item, nil } func scanUserDetail(row genericrepo.Scanner) (user.UserDTO, error) { var item user.UserDTO var roleID sql.NullInt64 var roleCode sql.NullString var branchesJSON []byte var permissionsJSON []byte if err := row.Scan( &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, &item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON, &permissionsJSON, ); err != nil { return user.UserDTO{}, err } applyJoinedRole(&item, roleID, roleCode) if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil { return user.UserDTO{}, err } if err := unmarshalJSON(permissionsJSON, &item.Permissions); err != nil { return user.UserDTO{}, err } if item.Branches == nil { item.Branches = []user.StaffBranchDTO{} } if item.Permissions == nil { item.Permissions = []user.UserPermissionDTO{} } return item, nil } func unmarshalJSON(raw []byte, dest interface{}) error { if len(raw) == 0 || string(raw) == "null" { return nil } return json.Unmarshal(raw, dest) } func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) { if roleCode.Valid { item.Role = roleCode.String } if roleID.Valid { id := roleID.Int64 item.RoleId = &id } }