settings section
This commit is contained in:
189
internal/admin/loansdocument/db/postgresql.go
Normal file
189
internal/admin/loansdocument/db/postgresql.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/loansdocument"
|
||||
"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) loansdocument.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const documentColumns = `d.id, d.title, d.content_en, d.content_ru, d.content_tm, d.status, d.created_at, d.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, 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 loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY d.id LIMIT $%d OFFSET $%d`,
|
||||
documentColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []loansdocument.LoanDocumentDTO
|
||||
for rows.Next() {
|
||||
item, err := scanLoanDocument(rows)
|
||||
if err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
return loansdocument.ListLoanDocumentDTO{Count: count, LoansDocuments: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM loans_documents d`
|
||||
|
||||
var conditions []string
|
||||
|
||||
if filter.DocumentName != "" {
|
||||
args = append(args, likePattern(filter.DocumentName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
d.title->>'en' ILIKE $%[1]d OR d.title->>'ru' ILIKE $%[1]d OR d.title->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("d.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
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) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM loans_documents d WHERE d.id = $1`, documentColumns)
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
title, err := json.Marshal(dto.Title)
|
||||
if err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
status := true
|
||||
if dto.Status != nil {
|
||||
status = *dto.Status
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loans_documents (title, content_en, content_ru, content_tm, status)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING %s`, documentColumns)
|
||||
|
||||
return scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, status))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.UpdateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
title, err := json.Marshal(dto.Title)
|
||||
if err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loans_documents SET
|
||||
title = $1, content_en = $2, content_ru = $3, content_tm = $4, status = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING %s`, documentColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, dto.Status, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loans_documents SET
|
||||
status = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2
|
||||
RETURNING %s`, documentColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, status, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM loans_documents 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 scanLoanDocument(row scannable) (loansdocument.LoanDocumentDTO, error) {
|
||||
var item loansdocument.LoanDocumentDTO
|
||||
var titleJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &titleJSON, &item.ContentEn, &item.ContentRu, &item.ContentTm,
|
||||
&item.Status, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
52
internal/admin/loansdocument/dto.go
Normal file
52
internal/admin/loansdocument/dto.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package loansdocument
|
||||
|
||||
import "time"
|
||||
|
||||
type LocalizedTitle struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type LoanDocumentDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
Status bool `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanDocumentDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
ContentEn string `json:"contentEn" binding:"required"`
|
||||
ContentRu string `json:"contentRu" binding:"required"`
|
||||
ContentTm string `json:"contentTm" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
ContentEn string `json:"contentEn" binding:"required"`
|
||||
ContentRu string `json:"contentRu" binding:"required"`
|
||||
ContentTm string `json:"contentTm" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentStatusDTO struct {
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
DocumentName string
|
||||
Status *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanDocumentDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoansDocuments []LoanDocumentDTO `json:"loansDocuments"`
|
||||
}
|
||||
293
internal/admin/loansdocument/handler.go
Normal file
293
internal/admin/loansdocument/handler.go
Normal file
@@ -0,0 +1,293 @@
|
||||
package loansdocument
|
||||
|
||||
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 = "/loans-documents"
|
||||
|
||||
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.PATCH("/:id/status", h.updateStatus)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan documents
|
||||
// @Description Returns paginated loan documents with optional filters
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param document_name query string false "Filter by title (en, ru, tm)"
|
||||
// @Param status query bool false "Filter by status"
|
||||
// @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 /loans-documents [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 loan documents failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan document by ID
|
||||
// @Description Returns a single loan document
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan document
|
||||
// @Description Creates a new loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanDocumentDTO true "Loan document payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanDocumentDTO
|
||||
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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan document
|
||||
// @Description Updates an existing loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Param body body UpdateLoanDocumentDTO true "Loan document payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{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 UpdateLoanDocumentDTO
|
||||
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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// updateStatus godoc
|
||||
// @Summary Update loan document status
|
||||
// @Description Enables or disables a loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Param body body UpdateLoanDocumentStatusDTO true "Status payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{id}/status [patch]
|
||||
func (h *handler) updateStatus(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLoanDocumentStatusDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.UpdateStatus(c.Request.Context(), id, dto.Status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update loan document status failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan document
|
||||
// @Description Deletes a loan document
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan document 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("document_name")); raw != "" {
|
||||
filter.DocumentName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("status"); raw != "" {
|
||||
status, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Status = &status
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
12
internal/admin/loansdocument/storage.go
Normal file
12
internal/admin/loansdocument/storage.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package loansdocument
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanDocumentDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanDocumentDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanDocumentDTO) (LoanDocumentDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanDocumentDTO) (LoanDocumentDTO, error)
|
||||
UpdateStatus(ctx context.Context, id int64, status bool) (LoanDocumentDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in New Issue
Block a user