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

BIN
internal/admin/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,58 @@
package db
import (
"context"
"strconv"
"online-back/internal/admin/auth"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Repository {
return &repository{
client: client,
logger: logger,
}
}
const (
loginQuery = `SELECT id, password FROM admin WHERE login = $1`
adminQuery = `SELECT id, password FROM admin WHERE id = $1`
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
FROM admin WHERE id = $1`
)
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) {
var result auth.ResLoginDTO
err := r.client.QueryRow(ctx, loginQuery, dto.Login).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
var result auth.ResLoginDTO
err := r.client.QueryRow(ctx, adminQuery, id).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetProfile(ctx context.Context, id string) (auth.ResUserDTO, error) {
var profile auth.ResUserDTO
adminID, err := strconv.Atoi(id)
if err != nil {
return profile, err
}
err = r.client.QueryRow(ctx, profileQuery, adminID).Scan(
&profile.Id,
&profile.FullName,
&profile.PhoneNumber,
&profile.Avatar,
&profile.CreatedAt,
)
return profile, err
}

25
internal/admin/auth/dto.go Executable file
View File

@@ -0,0 +1,25 @@
package auth
import "time"
type LoginDTO struct {
Login string `json:"login" binding:"required"`
Password string `json:"password" binding:"required"`
}
type ResLoginDTO struct {
Id int `json:"id"`
Password string `json:"-"`
}
type TokenReqBody struct {
RefreshToken string `json:"refreshToken" binding:"required"`
}
type ResUserDTO struct {
Id int `json:"id"`
FullName string `json:"fullName"`
PhoneNumber string `json:"phoneNumber"`
Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"`
}

View File

@@ -0,0 +1,35 @@
package auth
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
func imageStorageDir(publicRoot string) string {
return filepath.Join(publicRoot, "images")
}
func imagePublicPath(filename string) string {
return "/images/" + filename
}
func resolveImagePath(publicRoot, filename string) (string, error) {
if filename == "" || strings.Contains(filename, "..") || strings.ContainsAny(filename, `/\`) {
return "", fmt.Errorf("invalid file name")
}
base := filepath.Clean(imageStorageDir(publicRoot))
path := filepath.Clean(filepath.Join(base, filepath.Base(filename)))
if !strings.HasPrefix(path, base+string(os.PathSeparator)) && path != base {
return "", fmt.Errorf("invalid file path")
}
return path, nil
}
func newUploadFilename(original string) string {
return fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(original))
}

225
internal/admin/auth/handler.go Executable file
View File

@@ -0,0 +1,225 @@
package auth
import (
"fmt"
"net/http"
"os"
"path/filepath"
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/handlers"
"online-back/pkg/logging"
"online-back/pkg/utils"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
const (
loginURL = "/login"
tokenURL = "/token"
getProfileURL = "/get-profile"
fileUploadURL = "/file"
fileRemoveURL = "/file/:id"
)
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) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.token)
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.deleteObject)
}
// login godoc
// @Description login for Admin
// @Tags auth
// @Accept json
// @Produce json
// @Param auth body LoginDTO true "Login JSON"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) {
var loginReq LoginDTO
if err := c.ShouldBindJSON(&loginReq); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
ctx := c.Request.Context()
res, err := h.repository.Login(ctx, loginReq)
if err != nil {
h.logger.Errorf("login lookup failed: %v", err)
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(res.Password), []byte(loginReq.Password)); err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(res.Id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// token godoc
// @Description refresh admin tokens
// @Tags auth
// @Accept json
// @Produce json
// @Param auth body TokenReqBody true "Token JSON"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /token [post]
func (h *handler) token(c *gin.Context) {
var tokenReq TokenReqBody
if err := c.ShouldBindJSON(&tokenReq); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
claims, err := utils.ParseRefreshToken(tokenReq.RefreshToken)
if err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
id, ok := utils.ClaimID(claims)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
admin, err := h.repository.CheckAdmin(c.Request.Context(), id)
if err != nil || admin.Id != id {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
tokenPair, err := utils.GenerateTokenPair(id)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// getProfile godoc
// @Description profile data for Admin
// @Tags admin
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /get-profile [get]
func (h *handler) getProfile(c *gin.Context) {
adminID, _ := c.Get("id")
profile, err := h.repository.GetProfile(c.Request.Context(), fmt.Sprint(adminID))
if err != nil {
h.logger.Errorf("get profile failed: %v", err)
c.JSON(http.StatusBadRequest, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
}
// fileUpload godoc
// @Description file upload
// @Tags file-upload
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "upload file"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file [post]
func (h *handler) fileUpload(c *gin.Context) {
header, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
cfg := config.GetConfig()
dir := imageStorageDir(cfg.PublicFilePath)
if err := os.MkdirAll(dir, 0755); err != nil {
h.logger.Errorf("create upload dir failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
filename := newUploadFilename(header.Filename)
if err := c.SaveUploadedFile(header, filepath.Join(dir, filename)); err != nil {
h.logger.Errorf("save upload failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(imagePublicPath(filename)))
}
// GetObject serves uploaded images from local storage.
func GetObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
content, err := os.ReadFile(path)
if err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.Data(http.StatusOK, http.DetectContentType(content), content)
}
// deleteObject godoc
// @Description remove file
// @Tags file-upload
// @Accept json
// @Produce json
// @Param id path string true "file name"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file/{id} [delete]
func (h *handler) deleteObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
if err := os.Remove(path); err != nil {
h.logger.Errorf("delete file failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
}

9
internal/admin/auth/storage.go Executable file
View File

@@ -0,0 +1,9 @@
package auth
import "context"
type Repository interface {
Login(ctx context.Context, dto LoginDTO) (ResLoginDTO, error)
CheckAdmin(ctx context.Context, id int) (ResLoginDTO, error)
GetProfile(ctx context.Context, req string) (ResUserDTO, error)
}

View File

@@ -0,0 +1,260 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/branches"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Repository {
return &repository{client: client, logger: logger}
}
const branchColumns = `b.id, b.title, b.province_id, b.location_id, b.unikal_nomer, b.address,
b.billing_login, b.billing_password, b.billing_username_sber, b.billing_password_sber,
b.billing_username_visa, b.billing_password_visa`
func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, 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 branches.ListBranchDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY b.id LIMIT $%d OFFSET $%d`,
branchColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
listArgs := append(args, filter.Limit, offset)
rows, err := r.client.Query(ctx, listQuery, listArgs...)
if err != nil {
return branches.ListBranchDTO{}, err
}
defer rows.Close()
var items []branches.BranchDTO
for rows.Next() {
item, err := scanBranch(rows)
if err != nil {
return branches.ListBranchDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return branches.ListBranchDTO{}, err
}
return branches.ListBranchDTO{Count: count, Branches: items}, nil
}
func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM branches b`
if filter.ProvinceName != "" {
fromClause += ` JOIN province p ON p.id = b.province_id`
}
var conditions []string
if filter.ProvinceID != nil {
args = append(args, *filter.ProvinceID)
conditions = append(conditions, fmt.Sprintf("b.province_id = $%d", len(args)))
}
if filter.LocationID != nil {
args = append(args, *filter.LocationID)
conditions = append(conditions, fmt.Sprintf("b.location_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.BranchName != "" {
args = append(args, likePattern(filter.BranchName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
b.title->>'en' ILIKE $%[1]d OR b.title->>'ru' ILIKE $%[1]d OR b.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.UnikalNomer != "" {
args = append(args, likePattern(filter.UnikalNomer))
n := len(args)
conditions = append(conditions, fmt.Sprintf("b.unikal_nomer 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) (branches.BranchDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM branches b WHERE b.id = $1`, branchColumns)
row := r.client.QueryRow(ctx, query, id)
item, err := scanBranch(row)
if errors.Is(err, pgx.ErrNoRows) {
return branches.BranchDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (branches.BranchDTO, error) {
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
return branches.BranchDTO{}, err
}
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
query := fmt.Sprintf(`
INSERT INTO branches (
title, province_id, location_id, unikal_nomer, address,
billing_login, billing_password, billing_username_sber, billing_password_sber,
billing_username_visa, billing_password_visa
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa,
)
item, err := scanBranch(row)
if isUniqueViolation(err) {
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
}
return item, err
}
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
return branches.BranchDTO{}, err
}
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
if err != nil {
return branches.BranchDTO{}, err
}
query := fmt.Sprintf(`
UPDATE branches SET
title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5,
billing_login = $6, billing_password = $7, billing_username_sber = $8,
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11
WHERE id = $12
RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa, id,
)
item, err := scanBranch(row)
if errors.Is(err, pgx.ErrNoRows) {
return branches.BranchDTO{}, err
}
if isUniqueViolation(err) {
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM branches WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func (r *repository) ensureRelations(ctx context.Context, provinceID, locationID int64) error {
var id int64
err := r.client.QueryRow(ctx,
`SELECT id FROM location WHERE id = $1 AND province_id = $2`, locationID, provinceID,
).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("location not found in province")
}
return err
}
func marshalBranchJSON(title, address branches.LocalizedText) ([]byte, []byte, error) {
titleJSON, err := json.Marshal(title)
if err != nil {
return nil, nil, err
}
addressJSON, err := json.Marshal(address)
if err != nil {
return nil, nil, err
}
return titleJSON, addressJSON, nil
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanBranch(row scannable) (branches.BranchDTO, error) {
var item branches.BranchDTO
var titleJSON, addressJSON []byte
err := row.Scan(
&item.Id, &titleJSON, &item.ProvinceId, &item.LocationId, &item.UnikalNomer, &addressJSON,
&item.BillingLogin, &item.BillingPassword, &item.BillingUsernameSber, &item.BillingPasswordSber,
&item.BillingUsernameVisa, &item.BillingPasswordVisa,
)
if err != nil {
return branches.BranchDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return branches.BranchDTO{}, err
}
if err := json.Unmarshal(addressJSON, &item.Address); err != nil {
return branches.BranchDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,65 @@
package branches
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type BranchDTO struct {
Id int64 `json:"id"`
Title LocalizedText `json:"title"`
ProvinceId int64 `json:"provinceId"`
LocationId int64 `json:"locationId"`
UnikalNomer string `json:"unikalNomer"`
Address LocalizedText `json:"address"`
BillingLogin string `json:"billingLogin"`
BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"`
}
type CreateBranchDTO struct {
Title LocalizedText `json:"title" binding:"required"`
ProvinceId int64 `json:"provinceId" binding:"required"`
LocationId int64 `json:"locationId" binding:"required"`
UnikalNomer string `json:"unikalNomer" binding:"required"`
Address LocalizedText `json:"address" binding:"required"`
BillingLogin string `json:"billingLogin"`
BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"`
}
type UpdateBranchDTO struct {
Title LocalizedText `json:"title" binding:"required"`
ProvinceId int64 `json:"provinceId" binding:"required"`
LocationId int64 `json:"locationId" binding:"required"`
UnikalNomer string `json:"unikalNomer" binding:"required"`
Address LocalizedText `json:"address" binding:"required"`
BillingLogin string `json:"billingLogin"`
BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"`
}
type ListFilter struct {
ProvinceID *int64
LocationID *int64
ProvinceName string
BranchName string
UnikalNomer string
Page int
Limit int
}
type ListBranchDTO struct {
Count int64 `json:"count"`
Branches []BranchDTO `json:"branches"`
}

View File

@@ -0,0 +1,283 @@
package branches
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 = "/branches"
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 branches
// @Description Returns paginated branches with optional filters
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param province_id query int false "Filter by province ID"
// @Param location_id query int false "Filter by location ID"
// @Param province_name query string false "Filter by province name (en, ru, tm)"
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
// @Param unikal_nomer query string false "Filter by unique number"
// @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 /branches [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 branches failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get branch by ID
// @Description Returns a single branch
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create branch
// @Description Creates a new branch
// @Tags branches
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateBranchDTO true "Branch payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches [post]
func (h *handler) create(c *gin.Context) {
var dto CreateBranchDTO
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 isClientError(err) {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
h.logger.Errorf("create branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update branch
// @Description Updates an existing branch
// @Tags branches
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Param body body UpdateBranchDTO true "Branch payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 UpdateBranchDTO
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 isClientError(err) {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
h.logger.Errorf("update branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete branch
// @Description Deletes a branch
// @Tags branches
// @Produce json
// @Security BearerAuth
// @Param id path int true "Branch ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /branches/{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 branch failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("branch removed"))
}
func isClientError(err error) bool {
msg := err.Error()
return msg == "location not found in province" || msg == "unikal nomer already exists"
}
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("location_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.LocationID = &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("branch_name")); raw != "" {
filter.BranchName = raw
}
if raw := strings.TrimSpace(c.Query("unikal_nomer")); raw != "" {
filter.UnikalNomer = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package branches
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListBranchDTO, error)
GetByID(ctx context.Context, id int64) (BranchDTO, error)
Create(ctx context.Context, dto CreateBranchDTO) (BranchDTO, error)
Update(ctx context.Context, id int64, dto UpdateBranchDTO) (BranchDTO, error)
Delete(ctx context.Context, id int64) error
}

View 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
}

View 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"`
}

View 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
}

View 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
}

View File

@@ -0,0 +1,177 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/loantype"
"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) loantype.Repository {
return &repository{client: client, logger: logger}
}
const loanTypeColumns = `lt.id, lt.title, lt.tax, lt.loan_term, lt.content, lt.created_at, lt.updated_at`
func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, 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 loantype.ListLoanTypeDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY lt.id LIMIT $%d OFFSET $%d`,
loanTypeColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return loantype.ListLoanTypeDTO{}, err
}
defer rows.Close()
var items []loantype.LoanTypeDTO
for rows.Next() {
item, err := scanLoanType(rows)
if err != nil {
return loantype.ListLoanTypeDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return loantype.ListLoanTypeDTO{}, err
}
return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil
}
func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM loan_types lt`
var conditions []string
if filter.LoanTypeName != "" {
args = append(args, likePattern(filter.LoanTypeName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
lt.title->>'en' ILIKE $%[1]d OR lt.title->>'ru' ILIKE $%[1]d OR lt.title->>'tm' ILIKE $%[1]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) (loantype.LoanTypeDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loan_types lt WHERE lt.id = $1`, loanTypeColumns)
item, err := scanLoanType(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return loantype.LoanTypeDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return loantype.LoanTypeDTO{}, err
}
query := fmt.Sprintf(`
INSERT INTO loan_types (title, tax, loan_term, content)
VALUES ($1, $2, $3, $4)
RETURNING %s`, loanTypeColumns)
return scanLoanType(r.client.QueryRow(ctx, query, title, dto.Tax, dto.LoanTerm, content))
}
func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return loantype.LoanTypeDTO{}, err
}
query := fmt.Sprintf(`
UPDATE loan_types SET
title = $1, tax = $2, loan_term = $3, content = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5
RETURNING %s`, loanTypeColumns)
item, err := scanLoanType(r.client.QueryRow(ctx, query, title, dto.Tax, dto.LoanTerm, content, id))
if errors.Is(err, pgx.ErrNoRows) {
return loantype.LoanTypeDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loan_types WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) {
titleJSON, err := json.Marshal(title)
if err != nil {
return nil, nil, err
}
contentJSON, err := json.Marshal(content)
if err != nil {
return nil, nil, err
}
return titleJSON, contentJSON, nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanLoanType(row scannable) (loantype.LoanTypeDTO, error) {
var item loantype.LoanTypeDTO
var titleJSON, contentJSON []byte
if err := row.Scan(
&item.Id, &titleJSON, &item.Tax, &item.LoanTerm, &contentJSON, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return loantype.LoanTypeDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return loantype.LoanTypeDTO{}, err
}
if err := json.Unmarshal(contentJSON, &item.Content); err != nil {
return loantype.LoanTypeDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,44 @@
package loantype
import "time"
type LocalizedTitle struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type LoanTypeDTO struct {
Id int64 `json:"id"`
Title LocalizedTitle `json:"title"`
Tax float64 `json:"tax"`
LoanTerm string `json:"loanTerm"`
Content LocalizedTitle `json:"content"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateLoanTypeDTO struct {
Title LocalizedTitle `json:"title" binding:"required"`
Tax float64 `json:"tax" binding:"required"`
LoanTerm string `json:"loanTerm" binding:"required"`
Content LocalizedTitle `json:"content" binding:"required"`
}
type UpdateLoanTypeDTO struct {
Title LocalizedTitle `json:"title" binding:"required"`
Tax float64 `json:"tax" binding:"required"`
LoanTerm string `json:"loanTerm" binding:"required"`
Content LocalizedTitle `json:"content" binding:"required"`
}
type ListFilter struct {
LoanTypeName string
Page int
Limit int
}
type ListLoanTypeDTO struct {
Count int64 `json:"count"`
LoanTypes []LoanTypeDTO `json:"loanTypes"`
}

View File

@@ -0,0 +1,242 @@
package loantype
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 = "/loan-types"
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 loan types
// @Description Returns paginated loan types with optional filters
// @Tags loan-type
// @Produce json
// @Security BearerAuth
// @Param loan_type_name query string false "Filter by title (en, ru, tm)"
// @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 /loan-types [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 types failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get loan type by ID
// @Description Returns a single loan type
// @Tags loan-type
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan type ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-types/{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 type failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create loan type
// @Description Creates a new loan type
// @Tags loan-type
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateLoanTypeDTO true "Loan type payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-types [post]
func (h *handler) create(c *gin.Context) {
var dto CreateLoanTypeDTO
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 type failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update loan type
// @Description Updates an existing loan type
// @Tags loan-type
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan type ID"
// @Param body body UpdateLoanTypeDTO true "Loan type payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-types/{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 UpdateLoanTypeDTO
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 type failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete loan type
// @Description Deletes a loan type
// @Tags loan-type
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan type ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-types/{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 type failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("loan type 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("loan_type_name")); raw != "" {
filter.LoanTypeName = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package loantype
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListLoanTypeDTO, error)
GetByID(ctx context.Context, id int64) (LoanTypeDTO, error)
Create(ctx context.Context, dto CreateLoanTypeDTO) (LoanTypeDTO, error)
Update(ctx context.Context, id int64, dto UpdateLoanTypeDTO) (LoanTypeDTO, error)
Delete(ctx context.Context, id int64) error
}

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
}

View File

@@ -0,0 +1,200 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/paymentcard"
"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) paymentcard.Repository {
return &repository{client: client, logger: logger}
}
const cardColumns = `c.id, c.price, c.title, c.content, c.status`
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, 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 paymentcard.ListPaymentCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
defer rows.Close()
var items []paymentcard.PaymentCardDTO
for rows.Next() {
item, err := scanPaymentCard(rows)
if err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return paymentcard.ListPaymentCardDTO{}, err
}
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
}
func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM payment_cards c`
var conditions []string
if filter.CardName != "" {
args = append(args, likePattern(filter.CardName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
c.title->>'en' ILIKE $%[1]d OR c.title->>'ru' ILIKE $%[1]d OR c.title->>'tm' ILIKE $%[1]d
)`, n))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("c.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) (paymentcard.PaymentCardDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM payment_cards c WHERE c.id = $1`, cardColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return paymentcard.PaymentCardDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return paymentcard.PaymentCardDTO{}, err
}
status := true
if dto.Status != nil {
status = *dto.Status
}
query := fmt.Sprintf(`
INSERT INTO payment_cards (price, title, content, status)
VALUES ($1, $2, $3, $4)
RETURNING %s`, cardColumns)
return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, status))
}
func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.UpdatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return paymentcard.PaymentCardDTO{}, err
}
query := fmt.Sprintf(`
UPDATE payment_cards SET
price = $1, title = $2, content = $3, status = $4
WHERE id = $5
RETURNING %s`, cardColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, dto.Status, id))
if errors.Is(err, pgx.ErrNoRows) {
return paymentcard.PaymentCardDTO{}, err
}
return item, err
}
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (paymentcard.PaymentCardDTO, error) {
query := fmt.Sprintf(`
UPDATE payment_cards SET status = $1
WHERE id = $2
RETURNING %s`, cardColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, status, id))
if errors.Is(err, pgx.ErrNoRows) {
return paymentcard.PaymentCardDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM payment_cards WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func marshalJSON(title, content paymentcard.LocalizedText) ([]byte, []byte, error) {
titleJSON, err := json.Marshal(title)
if err != nil {
return nil, nil, err
}
contentJSON, err := json.Marshal(content)
if err != nil {
return nil, nil, err
}
return titleJSON, contentJSON, nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) {
var item paymentcard.PaymentCardDTO
var titleJSON, contentJSON []byte
if err := row.Scan(
&item.Id, &item.Price, &titleJSON, &contentJSON, &item.Status,
); err != nil {
return paymentcard.PaymentCardDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return paymentcard.PaymentCardDTO{}, err
}
if err := json.Unmarshal(contentJSON, &item.Content); err != nil {
return paymentcard.PaymentCardDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,45 @@
package paymentcard
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type PaymentCardDTO struct {
Id int64 `json:"id"`
Price float64 `json:"price"`
Title LocalizedText `json:"title"`
Content LocalizedText `json:"content"`
Status bool `json:"status"`
}
type CreatePaymentCardDTO struct {
Price float64 `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Content LocalizedText `json:"content" binding:"required"`
Status *bool `json:"status"`
}
type UpdatePaymentCardDTO struct {
Price float64 `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Content LocalizedText `json:"content" binding:"required"`
Status bool `json:"status"`
}
type UpdatePaymentCardStatusDTO struct {
Status bool `json:"status"`
}
type ListFilter struct {
CardName string
Status *bool
Page int
Limit int
}
type ListPaymentCardDTO struct {
Count int64 `json:"count"`
PaymentCards []PaymentCardDTO `json:"paymentCards"`
}

View File

@@ -0,0 +1,293 @@
package paymentcard
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 = "/payment-cards"
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 payment cards
// @Description Returns paginated payment cards with optional filters
// @Tags payment-card
// @Produce json
// @Security BearerAuth
// @Param card_name query string false "Filter by card 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 /payment-cards [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 payment cards failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get payment card by ID
// @Description Returns a single payment card
// @Tags payment-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{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 payment card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create payment card
// @Description Creates a new payment card
// @Tags payment-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreatePaymentCardDTO true "Payment card payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards [post]
func (h *handler) create(c *gin.Context) {
var dto CreatePaymentCardDTO
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 payment card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update payment card
// @Description Updates an existing payment card
// @Tags payment-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param body body UpdatePaymentCardDTO true "Payment card payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{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 UpdatePaymentCardDTO
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 payment card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// updateStatus godoc
// @Summary Update payment card status
// @Description Enables or disables a payment card
// @Tags payment-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param body body UpdatePaymentCardStatusDTO true "Status payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{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 UpdatePaymentCardStatusDTO
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 payment card status failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete payment card
// @Description Deletes a payment card
// @Tags payment-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{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 payment card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card 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("card_name")); raw != "" {
filter.CardName = 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 paymentcard
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPaymentCardDTO, error)
GetByID(ctx context.Context, id int64) (PaymentCardDTO, error)
Create(ctx context.Context, dto CreatePaymentCardDTO) (PaymentCardDTO, error)
Update(ctx context.Context, id int64, dto UpdatePaymentCardDTO) (PaymentCardDTO, error)
UpdateStatus(ctx context.Context, id int64, status bool) (PaymentCardDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,104 @@
package db
import (
"context"
"encoding/json"
"errors"
"online-back/internal/admin/province"
"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) province.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
rows, err := r.client.Query(ctx, `SELECT id, title FROM province ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var items []province.ProvinceDTO
for rows.Next() {
item, err := scanProvince(rows)
if err != nil {
return nil, err
}
items = append(items, item)
}
return items, rows.Err()
}
func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
row := r.client.QueryRow(ctx, `SELECT id, title FROM province WHERE id = $1`, id)
item, err := scanProvince(row)
if errors.Is(err, pgx.ErrNoRows) {
return province.ProvinceDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) {
title, err := json.Marshal(dto.Title)
if err != nil {
return province.ProvinceDTO{}, err
}
row := r.client.QueryRow(ctx, `INSERT INTO province (title) VALUES ($1) RETURNING id, title`, title)
return scanProvince(row)
}
func (r *repository) Update(ctx context.Context, id int64, dto province.UpdateProvinceDTO) (province.ProvinceDTO, error) {
title, err := json.Marshal(dto.Title)
if err != nil {
return province.ProvinceDTO{}, err
}
row := r.client.QueryRow(ctx,
`UPDATE province SET title = $1 WHERE id = $2 RETURNING id, title`,
title, id,
)
item, err := scanProvince(row)
if errors.Is(err, pgx.ErrNoRows) {
return province.ProvinceDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM province 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 scanProvince(row scannable) (province.ProvinceDTO, error) {
var item province.ProvinceDTO
var titleJSON []byte
if err := row.Scan(&item.Id, &titleJSON); err != nil {
return province.ProvinceDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return province.ProvinceDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,20 @@
package province
type LocalizedTitle struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type ProvinceDTO struct {
Id int64 `json:"id"`
Title LocalizedTitle `json:"title"`
}
type CreateProvinceDTO struct {
Title LocalizedTitle `json:"title" binding:"required"`
}
type UpdateProvinceDTO struct {
Title LocalizedTitle `json:"title" binding:"required"`
}

View File

@@ -0,0 +1,197 @@
package province
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/provinces"
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 provinces
// @Description Returns all provinces
// @Tags province
// @Produce json
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces [get]
func (h *handler) list(c *gin.Context) {
items, err := h.repository.List(c.Request.Context())
if err != nil {
h.logger.Errorf("list provinces failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(items))
}
// getByID godoc
// @Summary Get province by ID
// @Description Returns a single province
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create province
// @Description Creates a new province
// @Tags province
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateProvinceDTO true "Province payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces [post]
func (h *handler) create(c *gin.Context) {
var dto CreateProvinceDTO
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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update province
// @Description Updates an existing province
// @Tags province
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Param body body UpdateProvinceDTO true "Province payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 UpdateProvinceDTO
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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete province
// @Description Deletes a province and its locations
// @Tags province
// @Produce json
// @Security BearerAuth
// @Param id path int true "Province ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /provinces/{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 province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("province 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
}

View File

@@ -0,0 +1,11 @@
package province
import "context"
type Repository interface {
List(ctx context.Context) ([]ProvinceDTO, error)
GetByID(ctx context.Context, id int64) (ProvinceDTO, error)
Create(ctx context.Context, dto CreateProvinceDTO) (ProvinceDTO, error)
Update(ctx context.Context, id int64, dto UpdateProvinceDTO) (ProvinceDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,177 @@
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"online-back/internal/admin/reasonscard"
"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) reasonscard.Repository {
return &repository{client: client, logger: logger}
}
const reasonColumns = `r.id, r.title, r.price, r.content, r.created_at, r.updated_at`
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, 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 reasonscard.ListReasonCardDTO{}, 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`,
reasonColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
defer rows.Close()
var items []reasonscard.ReasonCardDTO
for rows.Next() {
item, err := scanReasonCard(rows)
if err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return reasonscard.ListReasonCardDTO{}, err
}
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
}
func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM reasons_cards r`
var conditions []string
if filter.ReasonName != "" {
args = append(args, likePattern(filter.ReasonName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
r.title->>'en' ILIKE $%[1]d OR r.title->>'ru' ILIKE $%[1]d OR r.title->>'tm' ILIKE $%[1]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) (reasonscard.ReasonCardDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM reasons_cards r WHERE r.id = $1`, reasonColumns)
item, err := scanReasonCard(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) {
return reasonscard.ReasonCardDTO{}, err
}
return item, err
}
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return reasonscard.ReasonCardDTO{}, err
}
query := fmt.Sprintf(`
INSERT INTO reasons_cards (title, price, content)
VALUES ($1, $2, $3)
RETURNING %s`, reasonColumns)
return scanReasonCard(r.client.QueryRow(ctx, query, title, dto.Price, content))
}
func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.UpdateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
title, content, err := marshalJSON(dto.Title, dto.Content)
if err != nil {
return reasonscard.ReasonCardDTO{}, err
}
query := fmt.Sprintf(`
UPDATE reasons_cards SET
title = $1, price = $2, content = $3,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
RETURNING %s`, reasonColumns)
item, err := scanReasonCard(r.client.QueryRow(ctx, query, title, dto.Price, content, id))
if errors.Is(err, pgx.ErrNoRows) {
return reasonscard.ReasonCardDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM reasons_cards WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func marshalJSON(title, content reasonscard.LocalizedText) ([]byte, []byte, error) {
titleJSON, err := json.Marshal(title)
if err != nil {
return nil, nil, err
}
contentJSON, err := json.Marshal(content)
if err != nil {
return nil, nil, err
}
return titleJSON, contentJSON, nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanReasonCard(row scannable) (reasonscard.ReasonCardDTO, error) {
var item reasonscard.ReasonCardDTO
var titleJSON, contentJSON []byte
if err := row.Scan(
&item.Id, &titleJSON, &item.Price, &contentJSON, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return reasonscard.ReasonCardDTO{}, err
}
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
return reasonscard.ReasonCardDTO{}, err
}
if err := json.Unmarshal(contentJSON, &item.Content); err != nil {
return reasonscard.ReasonCardDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,41 @@
package reasonscard
import "time"
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type ReasonCardDTO struct {
Id int64 `json:"id"`
Title LocalizedText `json:"title"`
Price float64 `json:"price"`
Content LocalizedText `json:"content"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price float64 `json:"price" binding:"required"`
Content LocalizedText `json:"content" binding:"required"`
}
type UpdateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price float64 `json:"price" binding:"required"`
Content LocalizedText `json:"content" binding:"required"`
}
type ListFilter struct {
ReasonName string
Page int
Limit int
}
type ListReasonCardDTO struct {
Count int64 `json:"count"`
ReasonCards []ReasonCardDTO `json:"reasonCards"`
}

View File

@@ -0,0 +1,242 @@
package reasonscard
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 = "/reasons-cards"
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 reason cards
// @Description Returns paginated reason cards with optional filters
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param reason_name query string false "Filter by title (en, ru, tm)"
// @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 /reasons-cards [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 reason cards failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get reason card by ID
// @Description Returns a single reason card
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create reason card
// @Description Creates a new reason card
// @Tags reason-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateReasonCardDTO true "Reason card payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards [post]
func (h *handler) create(c *gin.Context) {
var dto CreateReasonCardDTO
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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update reason card
// @Description Updates an existing reason card
// @Tags reason-card
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Param body body UpdateReasonCardDTO true "Reason card payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{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 UpdateReasonCardDTO
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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete reason card
// @Description Deletes a reason card
// @Tags reason-card
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{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 reason card failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("reason card 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("reason_name")); raw != "" {
filter.ReasonName = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package reasonscard
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListReasonCardDTO, error)
GetByID(ctx context.Context, id int64) (ReasonCardDTO, error)
Create(ctx context.Context, dto CreateReasonCardDTO) (ReasonCardDTO, error)
Update(ctx context.Context, id int64, dto UpdateReasonCardDTO) (ReasonCardDTO, error)
Delete(ctx context.Context, id int64) error
}