settings section

This commit is contained in:
2026-07-04 18:34:30 +05:00
parent bbe5d219ad
commit 0c717101da
2867 changed files with 1118596 additions and 1 deletions

View File

@@ -0,0 +1,222 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/location"
"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) location.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) List(ctx context.Context, filter location.ListFilter) (location.ListLocationDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*) ` + fromClause + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return location.ListLocationDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT l.id, l.province_id, l.title, l.status%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`,
fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
listArgs := append(args, filter.Limit, offset)
rows, err := r.client.Query(ctx, listQuery, listArgs...)
if err != nil {
return location.ListLocationDTO{}, err
}
defer rows.Close()
var items []location.LocationDTO
for rows.Next() {
item, err := scanLocation(rows)
if err != nil {
return location.ListLocationDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return location.ListLocationDTO{}, err
}
return location.ListLocationDTO{
Count: count,
Locations: items,
}, nil
}
func buildListQuery(filter location.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM location l`
if filter.ProvinceName != "" {
fromClause += ` JOIN province p ON p.id = l.province_id`
}
var conditions []string
if filter.ProvinceID != nil {
args = append(args, *filter.ProvinceID)
conditions = append(conditions, fmt.Sprintf("l.province_id = $%d", len(args)))
}
if filter.ProvinceName != "" {
args = append(args, likePattern(filter.ProvinceName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
p.title->>'en' ILIKE $%[1]d OR p.title->>'ru' ILIKE $%[1]d OR p.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.LocationName != "" {
args = append(args, likePattern(filter.LocationName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
l.title->>'en' ILIKE $%[1]d OR l.title->>'ru' ILIKE $%[1]d OR l.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("l.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) (location.LocationDTO, error) {
row := r.client.QueryRow(ctx,
`SELECT id, province_id, title, status FROM location WHERE id = $1`, id,
)
item, err := scanLocation(row)
if errors.Is(err, pgx.ErrNoRows) {
return location.LocationDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto location.CreateLocationDTO) (location.LocationDTO, error) {
if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil {
return location.LocationDTO{}, err
}
title, err := json.Marshal(dto.Title)
if err != nil {
return location.LocationDTO{}, err
}
status := true
if dto.Status != nil {
status = *dto.Status
}
row := r.client.QueryRow(ctx,
`INSERT INTO location (province_id, title, status) VALUES ($1, $2, $3)
RETURNING id, province_id, title, status`,
dto.ProvinceId, title, status,
)
return scanLocation(row)
}
func (r *repository) Update(ctx context.Context, id int64, dto location.UpdateLocationDTO) (location.LocationDTO, error) {
if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil {
return location.LocationDTO{}, err
}
title, err := json.Marshal(dto.Title)
if err != nil {
return location.LocationDTO{}, err
}
row := r.client.QueryRow(ctx,
`UPDATE location SET province_id = $1, title = $2, status = $3
WHERE id = $4
RETURNING id, province_id, title, status`,
dto.ProvinceId, title, dto.Status, id,
)
item, err := scanLocation(row)
if errors.Is(err, pgx.ErrNoRows) {
return location.LocationDTO{}, err
}
return item, err
}
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (location.LocationDTO, error) {
row := r.client.QueryRow(ctx,
`UPDATE location SET status = $1 WHERE id = $2
RETURNING id, province_id, title, status`,
status, id,
)
item, err := scanLocation(row)
if errors.Is(err, pgx.ErrNoRows) {
return location.LocationDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM location WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error {
var id int64
err := r.client.QueryRow(ctx, `SELECT id FROM province WHERE id = $1`, provinceID).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("province not found")
}
return err
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLocation(row scannable) (location.LocationDTO, error) {
var item location.LocationDTO
var titleJSON []byte
if err := row.Scan(&item.Id, &item.ProvinceId, &titleJSON, &item.Status); err != nil {
return location.LocationDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return location.LocationDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,44 @@
package location
type LocalizedTitle struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type LocationDTO struct {
Id int64 `json:"id"`
ProvinceId int64 `json:"provinceId"`
Title LocalizedTitle `json:"title"`
Status bool `json:"status"`
}
type CreateLocationDTO struct {
ProvinceId int64 `json:"provinceId" binding:"required"`
Title LocalizedTitle `json:"title" binding:"required"`
Status *bool `json:"status"`
}
type UpdateLocationDTO struct {
ProvinceId int64 `json:"provinceId" binding:"required"`
Title LocalizedTitle `json:"title" binding:"required"`
Status bool `json:"status"`
}
type UpdateLocationStatusDTO struct {
Status bool `json:"status"`
}
type ListFilter struct {
ProvinceID *int64
ProvinceName string
LocationName string
Status *bool
Page int
Limit int
}
type ListLocationDTO struct {
Count int64 `json:"count"`
Locations []LocationDTO `json:"locations"`
}

View File

@@ -0,0 +1,315 @@
package location
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 = "/locations"
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 locations
// @Description Returns paginated locations with optional filters
// @Tags location
// @Produce json
// @Security BearerAuth
// @Param province_id query int false "Filter by province ID"
// @Param province_name query string false "Filter by province name (en, ru, tm)"
// @Param location_name query string false "Filter by location name (en, ru, tm)"
// @Param status query bool false "Filter by location 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 /locations [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 locations failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get location by ID
// @Description Returns a single location
// @Tags location
// @Produce json
// @Security BearerAuth
// @Param id path int true "Location ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /locations/{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 location failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create location
// @Description Creates a new location in a province
// @Tags location
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateLocationDTO true "Location payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /locations [post]
func (h *handler) create(c *gin.Context) {
var dto CreateLocationDTO
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 {
if err.Error() == "province not found" {
c.JSON(http.StatusBadRequest, appresult.ErrNotFound)
return
}
h.logger.Errorf("create location failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update location
// @Description Updates an existing location
// @Tags location
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Location ID"
// @Param body body UpdateLocationDTO true "Location payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /locations/{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 UpdateLocationDTO
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 {
if err.Error() == "province not found" {
c.JSON(http.StatusBadRequest, appresult.ErrNotFound)
return
}
h.logger.Errorf("update location failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// updateStatus godoc
// @Summary Update location status
// @Description Enables or disables a location
// @Tags location
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Location ID"
// @Param body body UpdateLocationStatusDTO true "Status payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /locations/{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 UpdateLocationStatusDTO
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 location status failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete location
// @Description Deletes a location
// @Tags location
// @Produce json
// @Security BearerAuth
// @Param id path int true "Location ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /locations/{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 location failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("location 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("province_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.ProvinceID = &id
}
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("province_name")); raw != "" {
filter.ProvinceName = raw
}
if raw := strings.TrimSpace(c.Query("location_name")); raw != "" {
filter.LocationName = raw
}
if raw := c.Query("status"); raw != "" {
status, err := strconv.ParseBool(raw)
if err != nil {
return ListFilter{}, false
}
filter.Status = &status
}
return filter, true
}

View File

@@ -0,0 +1,12 @@
package location
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListLocationDTO, error)
GetByID(ctx context.Context, id int64) (LocationDTO, error)
Create(ctx context.Context, dto CreateLocationDTO) (LocationDTO, error)
Update(ctx context.Context, id int64, dto UpdateLocationDTO) (LocationDTO, error)
UpdateStatus(ctx context.Context, id int64, status bool) (LocationDTO, error)
Delete(ctx context.Context, id int64) error
}