add roles
This commit is contained in:
@@ -4,10 +4,10 @@ listen:
|
||||
port: 5050
|
||||
jwt_key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX@VCJ9.yueyJzdWIiOiIyNTEyNzMiLCJpYXQiOjE1MTYy#MzkwMjJ9.o_LoJm03CaE6!0dugdR8sjIuFgPxGT7I2W8NvugFqHRY
|
||||
storage:
|
||||
host: localhost
|
||||
# host: main-db
|
||||
port: 5424
|
||||
# port: 5432
|
||||
# host: localhost
|
||||
host: main-db
|
||||
# port: 5424
|
||||
port: 5432
|
||||
database: bank_db
|
||||
username: bank_admin
|
||||
password: bank@#23#@_password
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
DROP TABLE IF EXISTS roles;
|
||||
DROP TABLE IF EXISTS loan_order_required_docs;
|
||||
DROP TABLE IF EXISTS loan_types;
|
||||
DROP TABLE IF EXISTS card_states;
|
||||
|
||||
@@ -94,3 +94,11 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
@@ -1,4 +0,0 @@
|
||||
ALTER TABLE loan_order_required_docs RENAME COLUMN active TO status;
|
||||
ALTER TABLE card_types RENAME COLUMN active TO status;
|
||||
ALTER TABLE provinces RENAME COLUMN active TO status;
|
||||
ALTER TABLE users RENAME COLUMN active TO status;
|
||||
@@ -1,4 +0,0 @@
|
||||
ALTER TABLE users RENAME COLUMN status TO active;
|
||||
ALTER TABLE provinces RENAME COLUMN status TO active;
|
||||
ALTER TABLE card_types RENAME COLUMN status TO active;
|
||||
ALTER TABLE loan_order_required_docs RENAME COLUMN status TO active;
|
||||
BIN
internal/.DS_Store
vendored
BIN
internal/.DS_Store
vendored
Binary file not shown.
BIN
internal/admin/.DS_Store
vendored
BIN
internal/admin/.DS_Store
vendored
Binary file not shown.
146
internal/admin/role/db/postgresql.go
Normal file
146
internal/admin/role/db/postgresql.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/role"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
|
||||
|
||||
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
||||
roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []role.RoleDTO
|
||||
for rows.Next() {
|
||||
item, err := scanRole(rows)
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM roles r`
|
||||
|
||||
var conditions []string
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, likePattern(filter.RoleName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
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) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns)
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO roles (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE roles SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM roles WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanRole(row scannable) (role.RoleDTO, error) {
|
||||
var item role.RoleDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
35
internal/admin/role/dto.go
Normal file
35
internal/admin/role/dto.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package role
|
||||
|
||||
import "time"
|
||||
|
||||
type RoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateRoleDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateRoleDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
RoleName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListRoleDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Roles []RoleDTO `json:"roles"`
|
||||
}
|
||||
242
internal/admin/role/handler.go
Normal file
242
internal/admin/role/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package role
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/roles"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List roles
|
||||
// @Description Returns paginated roles with optional filters
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role_name query string false "Filter by name"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list roles failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get role by ID
|
||||
// @Description Returns a single role
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create role
|
||||
// @Description Creates a new role
|
||||
// @Tags role
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateRoleDTO true "Role payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateRoleDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update role
|
||||
// @Description Updates an existing role
|
||||
// @Tags role
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Param body body UpdateRoleDTO true "Role payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateRoleDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete role
|
||||
// @Description Deletes a role
|
||||
// @Tags role
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /roles/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("role removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("role_name")); raw != "" {
|
||||
filter.RoleName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/admin/role/storage.go
Normal file
11
internal/admin/role/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package role
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListRoleDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (RoleDTO, error)
|
||||
Create(ctx context.Context, dto CreateRoleDTO) (RoleDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateRoleDTO) (RoleDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import (
|
||||
provincedb "online-back/internal/admin/province/db"
|
||||
"online-back/internal/admin/reasonscard"
|
||||
reasonscarddb "online-back/internal/admin/reasonscard/db"
|
||||
"online-back/internal/admin/role"
|
||||
roledb "online-back/internal/admin/role/db"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
@@ -70,5 +72,6 @@ func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Hand
|
||||
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
|
||||
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
|
||||
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user