339 lines
9.7 KiB
Go
339 lines
9.7 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"online-back/internal/identity/user"
|
|
"online-back/pkg/client/postgresql"
|
|
"online-back/pkg/logging"
|
|
|
|
"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.role, u.active, u.created_at, u.updated_at`
|
|
|
|
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at`
|
|
|
|
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
|
|
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
|
}
|
|
|
|
func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
fromClause := ` FROM users u `
|
|
whereClause, args := buildStaffWhere(filter)
|
|
|
|
var count int64
|
|
countQuery := `SELECT COUNT(*)` + fromClause + 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, 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
|
|
ORDER BY b.id
|
|
) b
|
|
), '[]'::json)
|
|
%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 := 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{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`}
|
|
if filter.Username != "" {
|
|
args = append(args, likePattern(filter.Username))
|
|
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, len(args)))
|
|
}
|
|
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 := scanUser(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 = ` FROM users u `
|
|
|
|
var conditions []string
|
|
if filter.Username != "" {
|
|
args = append(args, likePattern(filter.Username))
|
|
n := len(args)
|
|
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
|
|
}
|
|
if len(roles) == 1 {
|
|
args = append(args, roles[0])
|
|
n := len(args)
|
|
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
|
|
} else 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))
|
|
}
|
|
conditions = append(conditions, fmt.Sprintf(`u.role IN (%s)`, strings.Join(placeholders, ", ")))
|
|
}
|
|
|
|
if len(conditions) == 0 {
|
|
return fromClause, "", args
|
|
}
|
|
|
|
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
|
}
|
|
|
|
func likePattern(term string) string {
|
|
term = strings.ReplaceAll(term, `\`, `\\`)
|
|
term = strings.ReplaceAll(term, `%`, `\%`)
|
|
term = strings.ReplaceAll(term, `_`, `\_`)
|
|
return "%" + term + "%"
|
|
}
|
|
|
|
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
|
|
excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`
|
|
if whereClause == "" {
|
|
whereClause = " WHERE " + excludeStaff
|
|
} else {
|
|
whereClause += " AND " + excludeStaff
|
|
}
|
|
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 FROM users u WHERE u.id = $1`, userColumns)
|
|
item, err := scanUser(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
|
|
}
|
|
|
|
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
|
|
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
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
tag, err := r.client.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return pgx.ErrNoRows
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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, `DELETE FROM role_user WHERE user_id = $1`, userID); err != nil {
|
|
return err
|
|
}
|
|
return assignRoleByCode(ctx, tx, userID, roleCode)
|
|
}
|
|
|
|
type scannable interface {
|
|
Scan(dest ...interface{}) error
|
|
}
|
|
|
|
func scanUser(row scannable) (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 scanStaffUser(row scannable) (user.UserDTO, error) {
|
|
var item user.UserDTO
|
|
var branchesJSON []byte
|
|
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, &branchesJSON,
|
|
); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
|
|
item.Branches = []user.StaffBranchDTO{}
|
|
return item, nil
|
|
}
|
|
if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return item, nil
|
|
}
|