fixed
This commit is contained in:
BIN
backend/internal/admin/.DS_Store
vendored
Normal file
BIN
backend/internal/admin/.DS_Store
vendored
Normal file
Binary file not shown.
88
backend/internal/admin/auth/db/postgresql.go
Executable file
88
backend/internal/admin/auth/db/postgresql.go
Executable file
@@ -0,0 +1,88 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) {
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where login = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, dto.Login).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
|
||||
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where id = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, uuid string) (auth.ResUserDTO, error) {
|
||||
|
||||
var (
|
||||
ad auth.ResUserDTO
|
||||
)
|
||||
id, _ := strconv.Atoi(uuid)
|
||||
|
||||
q := `select
|
||||
id, fullname,
|
||||
phone_number, avatar,
|
||||
created_at
|
||||
from admin
|
||||
where id = $1;`
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&ad.Id, &ad.FullName,
|
||||
&ad.PhoneNumber, &ad.Avatar,
|
||||
&ad.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return ad, err
|
||||
}
|
||||
|
||||
return ad, nil
|
||||
}
|
||||
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/logging"
|
||||
"errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"golang.org/x/net/context"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/pashagolub/pgxmock"
|
||||
)
|
||||
|
||||
var (
|
||||
// prepare mock
|
||||
colums = []string{"id", "password"}
|
||||
|
||||
// request
|
||||
req = auth.LoginDTO{
|
||||
Login: "admin@admin.com",
|
||||
}
|
||||
|
||||
// expected
|
||||
want = auth.ResLoginDTO{
|
||||
Id: 1,
|
||||
Password: "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i",
|
||||
}
|
||||
)
|
||||
|
||||
// Setup will prepare mock and account service instance
|
||||
func Run(t *testing.T) pgxmock.PgxPoolIface {
|
||||
t.Helper()
|
||||
mock, err := pgxmock.NewPool()
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error occur: %v\n", err)
|
||||
}
|
||||
defer mock.Close()
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
mock := Run(t)
|
||||
q := `select id, password from admin where login = $1 ;`
|
||||
|
||||
t.Run("EXPECT SUCCESS", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnRows(mock.NewRows(colums).
|
||||
AddRow(1, "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, got.Id, want.Id)
|
||||
assert.Equal(t, got, want)
|
||||
})
|
||||
|
||||
t.Run("EXPECT FAIL", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnError(errors.New("error getting user data"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
assert.Error(t, err)
|
||||
if got.Id == 0 {
|
||||
assert.Nil(t, nil)
|
||||
}
|
||||
})
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("there were unfulfilled expectation: %v\n", err)
|
||||
}
|
||||
}
|
||||
29
backend/internal/admin/auth/dto.go
Executable file
29
backend/internal/admin/auth/dto.go
Executable file
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Login string `json:"login" binding:"required" required:"this one failed" `
|
||||
Password string `json:"password" binding:"required" required:"this one failed"`
|
||||
}
|
||||
|
||||
type ResLoginDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type TokenReqBody struct {
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
|
||||
type ReqDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
|
||||
type ResUserDTO struct {
|
||||
Id int `json:"Id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
320
backend/internal/admin/auth/handler.go
Executable file
320
backend/internal/admin/auth/handler.go
Executable file
@@ -0,0 +1,320 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
_ "bankline/docs"
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/config"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"bankline/pkg/utils"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
minioUpload "bankline/pkg/minio"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
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.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
|
||||
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
|
||||
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject)
|
||||
router.POST(tokenURL, h.token)
|
||||
|
||||
}
|
||||
|
||||
// =================================================================================
|
||||
|
||||
// login godoc
|
||||
// @Description login for Admin
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body LoginDTO true "Login JSON"
|
||||
// @Success 200 {string} string true "token"
|
||||
// @Router /admin/login [post]
|
||||
func (h *handler) login(c *gin.Context) {
|
||||
|
||||
var (
|
||||
loginReq LoginDTO
|
||||
)
|
||||
if err := c.ShouldBindJSON(&loginReq); err != nil {
|
||||
fmt.Println("err in login", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.Login(context.TODO(), loginReq)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
password := []byte(fmt.Sprint(loginReq.Password))
|
||||
oldHash := []byte(fmt.Sprint(res.Password))
|
||||
errCompareHash := bcrypt.CompareHashAndPassword(oldHash, password)
|
||||
if errCompareHash != nil {
|
||||
fmt.Println("errCompareHash", errCompareHash)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
newTokenPair, err := utils.GenerateTokenPair(res.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = newTokenPair
|
||||
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// getProfile godoc
|
||||
// @Description profile data for Admin
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} ResUserDTO
|
||||
// @Router /admin/get-profile [get]
|
||||
func (h *handler) getProfile(c *gin.Context) {
|
||||
uuid := c.Keys["id"]
|
||||
fmt.Println("uuid ----", uuid)
|
||||
dt, err := h.repository.GetProfile(context.Background(), fmt.Sprint(uuid))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = dt
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// fileUpload godoc
|
||||
// @Description file upload
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param file formData file true "this is a test file"
|
||||
//
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/file [post]
|
||||
func (h *handler) fileUpload(c *gin.Context) {
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "get form err: %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
defer func(file multipart.File) {
|
||||
err := file.Close()
|
||||
if err != nil {
|
||||
fmt.Println("hello", err)
|
||||
}
|
||||
}(file)
|
||||
|
||||
cfg := config.GetConfig()
|
||||
appDirPath := cfg.PublicFilePath + "/images/"
|
||||
|
||||
err = os.MkdirAll(appDirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
fmt.Println("wwwww", err)
|
||||
}
|
||||
|
||||
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
||||
dbPath := "/images/" + appName
|
||||
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
ctx := context.Background()
|
||||
|
||||
if err := minioUpload.EnsureBucket(ctx, minioClient); err != nil {
|
||||
fmt.Println("ensure bucket:", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create MinIO bucket"})
|
||||
return
|
||||
}
|
||||
|
||||
size := header.Size
|
||||
if size <= 0 {
|
||||
size = -1
|
||||
}
|
||||
_, err = minioClient.PutObject(ctx, minioUpload.BucketName, appName, file, size, minio.PutObjectOptions{ContentType: contentType})
|
||||
if err != nil {
|
||||
fmt.Println("Error uploading file to MinIO:", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "File upload to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = dbPath
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func GetObject(c *gin.Context) {
|
||||
|
||||
id := c.Param("id")
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
object, err := minioClient.GetObject(context.Background(), minioUpload.BucketName, id, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
fmt.Println("Error connection:", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
contentBytes := StreamToByte(object)
|
||||
contentType := http.DetectContentType(contentBytes)
|
||||
c.Data(http.StatusOK, contentType, contentBytes)
|
||||
}
|
||||
|
||||
func StreamToByte(stream io.Reader) []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
_, _ = buf.ReadFrom(stream)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// DeleteObject godoc
|
||||
// @Description remove file
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
//
|
||||
// @Param id path string true "file path"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/file/{id} [delete]
|
||||
func (h *handler) DeleteObject(c *gin.Context) {
|
||||
|
||||
id := c.Param("id")
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
suc, err := DeleteItemInMinio(context.Background(), minioClient, id)
|
||||
if err != nil {
|
||||
fmt.Println("Error connection:", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
successResult := appresult.Success
|
||||
successResult.Data = suc
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
func DeleteItemInMinio(ctx context.Context, minioClient *minio.Client, value string) (string, error) {
|
||||
err := minioClient.RemoveObject(ctx, minioUpload.BucketName, value, minio.RemoveObjectOptions{GovernanceBypass: true})
|
||||
if err != nil {
|
||||
fmt.Println("error remove file in minio:", err)
|
||||
return "", err
|
||||
}
|
||||
return "File successfully removed!!!", nil
|
||||
}
|
||||
|
||||
// token godoc
|
||||
// @Description token for Admin
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body TokenReqBody true "Token JSON"
|
||||
// @Success 200 {string} string true "token"
|
||||
// @Router /admin/token [post]
|
||||
func (h *handler) token(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
tokenReq TokenReqBody
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&tokenReq); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(utils.SecretKey), nil
|
||||
})
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
|
||||
res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
if int(claims["id"].(float64)) == res.Id {
|
||||
|
||||
newTokenPair, err := utils.GenerateTokenPair(int(claims["id"].(float64)))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = newTokenPair
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
9
backend/internal/admin/auth/storage.go
Executable file
9
backend/internal/admin/auth/storage.go
Executable 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)
|
||||
}
|
||||
167
backend/internal/admin/banner/db/postgresql.go
Executable file
167
backend/internal/admin/banner/db/postgresql.go
Executable file
@@ -0,0 +1,167 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/banner"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) banner.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (banner.DataBannerDTO, error) {
|
||||
|
||||
ns := []banner.GetBannerDTO{}
|
||||
var (
|
||||
dt banner.DataBannerDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from banner` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
from banner` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n banner.GetBannerDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetOneData(ctx context.Context, id int) (banner.GetBannerDTO, error) {
|
||||
|
||||
var (
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
from banner where id = $1 ; `
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req banner.AddBannerDTO) (banner.GetBannerDTO, error) {
|
||||
var (
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO banner (title, content_tm, content_ru, content_en, img) VALUES ($1, $2, $3, $4, $5) RETURNING id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Image).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req banner.UpdateBannerDTO, id int) (banner.GetBannerDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q = ` update banner set title = $1, content_tm = $2, content_ru = $3, content_en = $4, img = $5 where id = $6 RETURNING id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Image, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, uuid int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from banner where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, uuid)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
48
backend/internal/admin/banner/dto.go
Executable file
48
backend/internal/admin/banner/dto.go
Executable file
@@ -0,0 +1,48 @@
|
||||
package banner
|
||||
|
||||
import "time"
|
||||
|
||||
type DataBannerDTO struct {
|
||||
Categories []GetBannerDTO `json:"banners"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type GetBannerDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddBannerDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
}
|
||||
|
||||
type UpdateBannerDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
}
|
||||
|
||||
type ReqUUIDDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
|
||||
type ReqIDDTO struct {
|
||||
Id int `json:"id"`
|
||||
}
|
||||
212
backend/internal/admin/banner/handler.go
Executable file
212
backend/internal/admin/banner/handler.go
Executable file
@@ -0,0 +1,212 @@
|
||||
package banner
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataBannerDTO
|
||||
// @Router /admin/banner [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Success 200 {object} GetBannerDTO
|
||||
// @Router /admin/banner/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
fmt.Println("--------------", id)
|
||||
i, err := strconv.Atoi(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
result, err := h.repository.GetOneData(context.Background(), i)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param banner body AddBannerDTO true "Create JSON"
|
||||
// @Success 200 {object} GetBannerDTO
|
||||
// @Router /admin/banner [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
)
|
||||
|
||||
body, errBody := io.ReadAll(c.Request.Body)
|
||||
if errBody != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
reqDTO := AddBannerDTO{}
|
||||
err = json.Unmarshal(body, &reqDTO)
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Param banner body UpdateBannerDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/banner/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
res GetBannerDTO
|
||||
)
|
||||
bannerId := c.Param("id")
|
||||
fmt.Println("--------------", bannerId)
|
||||
id, err := strconv.Atoi(bannerId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
body, errBody := io.ReadAll(c.Request.Body)
|
||||
if errBody != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
reqDTO := UpdateBannerDTO{}
|
||||
err = json.Unmarshal(body, &reqDTO)
|
||||
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/banner/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
bannerId := c.Param("id")
|
||||
fmt.Println("--------------", bannerId)
|
||||
id, err := strconv.Atoi(bannerId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/banner/model.go
Executable file
1
backend/internal/admin/banner/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package banner
|
||||
14
backend/internal/admin/banner/storage.go
Executable file
14
backend/internal/admin/banner/storage.go
Executable file
@@ -0,0 +1,14 @@
|
||||
package banner
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataBannerDTO, error)
|
||||
GetOneData(ctx context.Context, id int) (GetBannerDTO, error)
|
||||
AddData(ctx context.Context, dto AddBannerDTO) (GetBannerDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateBannerDTO, id int) (GetBannerDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
169
backend/internal/admin/category/db/postgresql.go
Executable file
169
backend/internal/admin/category/db/postgresql.go
Executable file
@@ -0,0 +1,169 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/category"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) category.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "cs.id",
|
||||
"status": "cs.status",
|
||||
"createdAt": "cs.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (category.DataCategoryDTO, error) {
|
||||
|
||||
ns := []category.CategoryDTO{}
|
||||
var (
|
||||
dt category.DataCategoryDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where cs.name::text ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from categories cs` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
cs.Id, cs.name,
|
||||
jsonb_agg(ss.name) as sub_category,
|
||||
cs.status, cs.created_at
|
||||
from categories cs
|
||||
left join sub_categories ss on ss.category_id = cs.Id ` +
|
||||
where +
|
||||
` group by cs.Id ` +
|
||||
params.OrderClause(sortColumns, "cs.created_at ASC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n category.CategoryDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Name, &n.SubName,
|
||||
&n.Status, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (category.CategoryDTO, error) {
|
||||
|
||||
var (
|
||||
ns category.CategoryDTO
|
||||
)
|
||||
|
||||
qC := `select id, name, status, created_at from categories where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(&ns.Id, &ns.Name, &ns.Status, &ns.CreatedAt)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req category.AddCategoryDTO) (category.CategoryIdDTO, error) {
|
||||
|
||||
var (
|
||||
n category.CategoryIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO categories (name) VALUES ($1) RETURNING id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Name).Scan(
|
||||
&n.Id, &n.Name, &n.Status,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req category.UpdateCategoryDTO, id int) (category.CategoryIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n category.CategoryIdDTO
|
||||
)
|
||||
|
||||
q = ` update categories set name = $1 where Id = $2 RETURNING id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Name, id).Scan(
|
||||
&n.Id, &n.Name, &n.Status,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateStatusData(ctx context.Context, status string, id int) (category.CategoryDTO, error) {
|
||||
|
||||
q := ` update categories set status = $1 where id = $2;`
|
||||
|
||||
_, err := r.client.Exec(ctx, q, status, id)
|
||||
|
||||
dt, err := r.GetData(ctx, id)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return dt, err
|
||||
}
|
||||
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, Id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from categories where Id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, Id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
49
backend/internal/admin/category/dto.go
Executable file
49
backend/internal/admin/category/dto.go
Executable file
@@ -0,0 +1,49 @@
|
||||
package category
|
||||
|
||||
import "time"
|
||||
|
||||
type DataCategoryDTO struct {
|
||||
Categories []CategoryDTO `json:"categories"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type CategoryDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Name Language `json:"name"`
|
||||
SubName []Language `json:"subCategories"`
|
||||
Status bool `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddCategoryDTO struct {
|
||||
Name Language `json:"name" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateCategoryDTO struct {
|
||||
Name Language `json:"name" binding:"required"`
|
||||
// Status intentionally has no "required" binding: the validator treats
|
||||
// false as a missing value, which would make it impossible to update a
|
||||
// disabled category.
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type CategoryIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Name Language `json:"name"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type PaginationDTO struct {
|
||||
Limit int `json:"limit"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
|
||||
type ReqIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
246
backend/internal/admin/category/handler.go
Executable file
246
backend/internal/admin/category/handler.go
Executable file
@@ -0,0 +1,246 @@
|
||||
package category
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
getStatusURL = "/:id/status"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.PUT(getStatusURL, h.UpdateStatus)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, status, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataCategoryDTO
|
||||
// @Router /admin/categories [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data category
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Success 200 {object} CategoryDTO
|
||||
// @Router /admin/categories/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param categories body AddCategoryDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/categories [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddCategoryDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Param categories body UpdateCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} CategoryIdDTO
|
||||
// @Router /admin/categories/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateCategoryDTO
|
||||
res CategoryIdDTO
|
||||
)
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err :::", err)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateStatus godoc
|
||||
// @Description update status categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category id"
|
||||
// @Param status query bool true "status"
|
||||
// @Success 200 {object} CategoryDTO
|
||||
// @Router /admin/categories/{id}/status [put]
|
||||
func (h *handler) UpdateStatus(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
res CategoryDTO
|
||||
)
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
status, _ := c.GetQuery("status")
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateStatusData(context.Background(), status, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete category
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/categories/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/category/model.go
Executable file
1
backend/internal/admin/category/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package category
|
||||
16
backend/internal/admin/category/storage.go
Executable file
16
backend/internal/admin/category/storage.go
Executable file
@@ -0,0 +1,16 @@
|
||||
package category
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataCategoryDTO, error)
|
||||
GetData(ctx context.Context, id int) (CategoryDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddCategoryDTO) (CategoryIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateCategoryDTO, id int) (CategoryIdDTO, error)
|
||||
UpdateStatusData(ctx context.Context, status string, id int) (CategoryDTO, error)
|
||||
DeleteData(ctx context.Context, uuid int) error
|
||||
}
|
||||
167
backend/internal/admin/currency/db/postgresql.go
Normal file
167
backend/internal/admin/currency/db/postgresql.go
Normal file
@@ -0,0 +1,167 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/currency"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) currency.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (currency.DataCurrencyDTO, error) {
|
||||
|
||||
ns := []currency.CurrencyDTO{}
|
||||
var (
|
||||
dt currency.DataCurrencyDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from currency` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
path, created_at
|
||||
from currency` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n currency.CurrencyDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Path, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Currencies = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (currency.CurrencyDTO, error) {
|
||||
|
||||
var (
|
||||
ns currency.CurrencyDTO
|
||||
)
|
||||
|
||||
qC := `select id, title, content_tm, content_ru, content_en, path, created_at from currency where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.Title,
|
||||
&ns.ContentTm, &ns.ContentRu, &ns.ContentEn,
|
||||
&ns.Path, &ns.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req currency.AddCurrencyDTO) (currency.CurrencyIdDTO, error) {
|
||||
|
||||
var (
|
||||
n currency.CurrencyIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO currency (title, content_tm, content_ru, content_en, path)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, title, path;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Path,
|
||||
).Scan(
|
||||
&n.Id, &n.Title, &n.Path,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req currency.UpdateCurrencyDTO, id int) (currency.CurrencyIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n currency.CurrencyIdDTO
|
||||
)
|
||||
|
||||
q = ` update currency set
|
||||
title = $1, content_tm = $2, content_ru = $3, content_en = $4, path = $5
|
||||
where id = $6
|
||||
RETURNING id, title, path;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Path,
|
||||
id,
|
||||
).Scan(
|
||||
&n.Id, &n.Title, &n.Path,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from currency where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
46
backend/internal/admin/currency/dto.go
Normal file
46
backend/internal/admin/currency/dto.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package currency
|
||||
|
||||
import "time"
|
||||
|
||||
type DataCurrencyDTO struct {
|
||||
Currencies []CurrencyDTO `json:"currencies"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type CurrencyDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddCurrencyDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateCurrencyDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path" binding:"required"`
|
||||
}
|
||||
|
||||
type CurrencyIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
203
backend/internal/admin/currency/handler.go
Normal file
203
backend/internal/admin/currency/handler.go
Normal file
@@ -0,0 +1,203 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data currencies
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataCurrencyDTO
|
||||
// @Router /admin/currency [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Router /admin/currency/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param currency body AddCurrencyDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/currency [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddCurrencyDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Param currency body UpdateCurrencyDTO true "Create JSON"
|
||||
// @Success 200 {object} CurrencyIdDTO
|
||||
// @Router /admin/currency/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateCurrencyDTO
|
||||
res CurrencyIdDTO
|
||||
)
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/currency/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
15
backend/internal/admin/currency/storage.go
Normal file
15
backend/internal/admin/currency/storage.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataCurrencyDTO, error)
|
||||
GetData(ctx context.Context, id int) (CurrencyDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddCurrencyDTO) (CurrencyIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateCurrencyDTO, id int) (CurrencyIdDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
201
backend/internal/admin/news/db/postgresql.go
Executable file
201
backend/internal/admin/news/db/postgresql.go
Executable file
@@ -0,0 +1,201 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/news"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) news.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "n.id",
|
||||
"dateRelease": "n.date_release",
|
||||
"createdAt": "n.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (news.DataNewsDTO, error) {
|
||||
var dt news.DataNewsDTO
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` WHERE n.title::text ILIKE $1 OR nc.tm ILIKE $1 OR nc.ru ILIKE $1 OR nc.en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `SELECT count(*) FROM news n LEFT JOIN news_content nc ON n.id = nc.news_id` + where + `;`
|
||||
if err := r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id ` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "n.date_release DESC")
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("LIMIT $%d OFFSET $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
r.logger.Error("get all news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ns := []news.GetNewsDTO{}
|
||||
for rows.Next() {
|
||||
var n news.GetNewsDTO
|
||||
if err = rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En,
|
||||
&n.Content.Tm, &n.Content.Ru,
|
||||
); err != nil {
|
||||
r.logger.Error("scan news :::", err)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetOneData(ctx context.Context, id int) (news.GetNewsDTO, error) {
|
||||
var n news.GetNewsDTO
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id
|
||||
WHERE n.id = $1; `
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En, &n.Content.Tm,
|
||||
&n.Content.Ru,
|
||||
)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req news.AddNewsDTO) (news.GetNewsDTO, error) {
|
||||
var (
|
||||
n news.GetNewsDTO
|
||||
lang news.Language
|
||||
)
|
||||
|
||||
q := `INSERT INTO news (title, img, date_release) VALUES ($1, $2, $3)
|
||||
RETURNING id, title, date_release, img;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.Image, req.DataRelease).Scan(
|
||||
&n.Id, &n.Title, &n.DataRelease, &n.Image,
|
||||
)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logger.Error("add news :::", err)
|
||||
return n, err
|
||||
}
|
||||
if n.Id != 0 {
|
||||
q = `INSERT INTO news_content (news_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
r.logger.Error("add news content :::", err)
|
||||
return n, err
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req news.UpdateNewsDTO, id int) (news.GetNewsDTO, error) {
|
||||
var (
|
||||
n news.GetNewsDTO
|
||||
lang news.Language
|
||||
)
|
||||
|
||||
q := ` update news set
|
||||
title = $1, img = $2, date_release = $3
|
||||
where id = $4 RETURNING id, title, date_release, img;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.Image, req.DataRelease,
|
||||
id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logger.Error("update news main :::", err)
|
||||
return n, err
|
||||
}
|
||||
if n.Id != 0 {
|
||||
q = ` UPDATE news_content SET en = $1, ru = $2, tm = $3 where news_id = $4 RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, req.Content.En, req.Content.Ru, req.Content.Tm, n.Id).Scan(&lang.En, &lang.Ru, &lang.Tm)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
q = `INSERT INTO news_content (news_id, en, ru, tm) VALUES ($1, $2, $3, $4) RETURNING en, ru, tm;`
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("update news content :::", err)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
q := ` delete from news where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
36
backend/internal/admin/news/dto.go
Executable file
36
backend/internal/admin/news/dto.go
Executable file
@@ -0,0 +1,36 @@
|
||||
package news
|
||||
|
||||
import "time"
|
||||
|
||||
type DataNewsDTO struct {
|
||||
Categories []GetNewsDTO `json:"news"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type GetNewsDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type AddNewsDTO struct {
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type UpdateNewsDTO struct {
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
177
backend/internal/admin/news/handler.go
Executable file
177
backend/internal/admin/news/handler.go
Executable file
@@ -0,0 +1,177 @@
|
||||
package news
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, dateRelease, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataNewsDTO
|
||||
// @Router /admin/news [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(c.Request.Context(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {object} GetNewsDTO
|
||||
// @Router /admin/news/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetOneData(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param news body AddNewsDTO true "Create JSON"
|
||||
// @Success 200 {object} GetNewsDTO
|
||||
// @Router /admin/news [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var reqDTO AddNewsDTO
|
||||
if err := c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(c.Request.Context(), reqDTO)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Param news body UpdateNewsDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/news/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
var reqDTO UpdateNewsDTO
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.UpdateData(c.Request.Context(), reqDTO, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/news/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
if err = h.repository.DeleteData(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
14
backend/internal/admin/news/storage.go
Executable file
14
backend/internal/admin/news/storage.go
Executable file
@@ -0,0 +1,14 @@
|
||||
package news
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataNewsDTO, error)
|
||||
GetOneData(ctx context.Context, id int) (GetNewsDTO, error)
|
||||
AddData(ctx context.Context, dto AddNewsDTO) (GetNewsDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateNewsDTO, id int) (GetNewsDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
79
backend/internal/admin/setting/db/postgresql.go
Executable file
79
backend/internal/admin/setting/db/postgresql.go
Executable file
@@ -0,0 +1,79 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/setting"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) setting.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context) (setting.SettingDTO, error) {
|
||||
q := `SELECT id, uuid::text, logo_r, phone_number, fax_number, help_number, created_at
|
||||
FROM setting ORDER BY id ASC LIMIT 1;`
|
||||
|
||||
var n setting.SettingDTO
|
||||
errN := r.client.QueryRow(ctx, q).Scan(
|
||||
&n.Id, &n.UUID, &n.LogoR, &n.PhoneNumber, &n.FaxNumber, &n.HelpNumber, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
if errN.Error() == "no rows in result set" {
|
||||
return n, nil
|
||||
}
|
||||
r.logger.Error("errN :::", errN)
|
||||
return n, errN
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req setting.UpdateSettingDTO, id int) (setting.SettingDTO, error) {
|
||||
q := `UPDATE setting SET
|
||||
logo_r = $1,
|
||||
phone_number = $2,
|
||||
fax_number = $3,
|
||||
help_number = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5;`
|
||||
|
||||
tag, err := r.client.Exec(ctx, q, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber, id)
|
||||
if err != nil {
|
||||
return setting.SettingDTO{}, err
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
// No matching row — insert (optionally with requested id).
|
||||
if id > 0 {
|
||||
q = `INSERT INTO setting (id, logo_r, phone_number, fax_number, help_number)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
logo_r = EXCLUDED.logo_r,
|
||||
phone_number = EXCLUDED.phone_number,
|
||||
fax_number = EXCLUDED.fax_number,
|
||||
help_number = EXCLUDED.help_number,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC');`
|
||||
_, err = r.client.Exec(ctx, q, id, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber)
|
||||
} else {
|
||||
q = `INSERT INTO setting (logo_r, phone_number, fax_number, help_number)
|
||||
VALUES ($1, $2, $3, $4);`
|
||||
_, err = r.client.Exec(ctx, q, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber)
|
||||
}
|
||||
if err != nil {
|
||||
return setting.SettingDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return r.GetData(ctx)
|
||||
}
|
||||
20
backend/internal/admin/setting/dto.go
Executable file
20
backend/internal/admin/setting/dto.go
Executable file
@@ -0,0 +1,20 @@
|
||||
package setting
|
||||
|
||||
import "time"
|
||||
|
||||
type SettingDTO struct {
|
||||
Id int `json:"Id"`
|
||||
UUID string `json:"UUID"`
|
||||
LogoR string `json:"logoR"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
FaxNumber string `json:"faxNumber"`
|
||||
HelpNumber string `json:"helpNumber"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UpdateSettingDTO struct {
|
||||
LogoR string `json:"logoR"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
FaxNumber string `json:"faxNumber"`
|
||||
HelpNumber string `json:"helpNumber"`
|
||||
}
|
||||
94
backend/internal/admin/setting/handler.go
Executable file
94
backend/internal/admin/setting/handler.go
Executable file
@@ -0,0 +1,94 @@
|
||||
package setting
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getURL = ""
|
||||
addURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getURL, h.GetOne)
|
||||
router.POST(addURL, h.Create)
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description get site setting
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /admin/setting [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
result, err := h.repository.GetData(context.Background())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description update site setting
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param settings body UpdateSettingDTO true "Update JSON"
|
||||
// @Param id path int true "setting id"
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /admin/setting/{id} [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateSettingDTO
|
||||
res SettingDTO
|
||||
)
|
||||
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
1
backend/internal/admin/setting/model.go
Executable file
1
backend/internal/admin/setting/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package setting
|
||||
8
backend/internal/admin/setting/storage.go
Executable file
8
backend/internal/admin/setting/storage.go
Executable file
@@ -0,0 +1,8 @@
|
||||
package setting
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
GetData(ctx context.Context) (SettingDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateSettingDTO, id int) (SettingDTO, error)
|
||||
}
|
||||
157
backend/internal/admin/static/db/postgresql.go
Normal file
157
backend/internal/admin/static/db/postgresql.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/static"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) static.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (static.DataStaticDTO, error) {
|
||||
|
||||
ns := []static.StaticDTO{}
|
||||
var (
|
||||
dt static.DataStaticDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from static` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
from static` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n static.StaticDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Statics = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (static.StaticDTO, error) {
|
||||
|
||||
var (
|
||||
ns static.StaticDTO
|
||||
)
|
||||
|
||||
qC := `select id, logo, title, content_tm, content_ru, content_en, created_at from static where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.Logo, &ns.Title,
|
||||
&ns.ContentTm, &ns.ContentRu, &ns.ContentEn,
|
||||
&ns.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req static.AddStaticDTO) (static.StaticIdDTO, error) {
|
||||
|
||||
var (
|
||||
n static.StaticIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO static (logo, title, content_tm, content_ru, content_en) VALUES ($1, $2, $3, $4, $5) RETURNING id, logo, title;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Logo, req.Title, req.ContentTm, req.ContentRu, req.ContentEn).Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req static.UpdateStaticDTO, id int) (static.StaticIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n static.StaticIdDTO
|
||||
)
|
||||
|
||||
q = ` update static set logo = $1, title = $2, content_tm = $3, content_ru = $4, content_en = $5 where id = $6 RETURNING id, logo, title;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Logo, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, id).Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from static where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
55
backend/internal/admin/static/dto.go
Normal file
55
backend/internal/admin/static/dto.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package static
|
||||
|
||||
import "time"
|
||||
|
||||
type DataStaticDTO struct {
|
||||
Statics []StaticDTO `json:"statics"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type StaticDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Logo string `json:"logo"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddStaticDTO struct {
|
||||
Logo string `json:"logo" binding:"required"`
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
}
|
||||
|
||||
type UpdateStaticDTO struct {
|
||||
Logo string `json:"logo" binding:"required"`
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
}
|
||||
|
||||
type StaticIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Logo string `json:"logo"`
|
||||
Title Language `json:"title"`
|
||||
}
|
||||
|
||||
type PaginationDTO struct {
|
||||
Limit int `json:"limit"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
|
||||
type ReqIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
206
backend/internal/admin/static/handler.go
Normal file
206
backend/internal/admin/static/handler.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataStaticDTO
|
||||
// @Router /admin/static [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data static
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {object} StaticDTO
|
||||
// @Router /admin/static/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param statics body AddStaticDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/static [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddStaticDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Param statics body UpdateStaticDTO true "Create JSON"
|
||||
// @Success 200 {object} StaticIdDTO
|
||||
// @Router /admin/static/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateStaticDTO
|
||||
res StaticIdDTO
|
||||
)
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err :::", err)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete static
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/static/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
15
backend/internal/admin/static/storage.go
Normal file
15
backend/internal/admin/static/storage.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataStaticDTO, error)
|
||||
GetData(ctx context.Context, id int) (StaticDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddStaticDTO) (StaticIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateStaticDTO, id int) (StaticIdDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
224
backend/internal/admin/sub_category/db/postgresql.go
Executable file
224
backend/internal/admin/sub_category/db/postgresql.go
Executable file
@@ -0,0 +1,224 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/sub_category"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) sub_category.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "sc.id",
|
||||
"status": "sc.status",
|
||||
"createdAt": "sc.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params, categoryId int) (sub_category.DataDTO, error) {
|
||||
|
||||
ns := []sub_category.SubCategoryDTO{}
|
||||
var (
|
||||
dt sub_category.DataDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ` where sc.category_id = $1 `
|
||||
args := []interface{}{categoryId}
|
||||
if params.Search != "" {
|
||||
where += ` and (sc.name::text ILIKE $2 OR scc.tm ILIKE $2 OR scc.ru ILIKE $2 OR scc.en ILIKE $2) `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(sc.*) from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := `select
|
||||
sc.id, sc.status,
|
||||
sc.name, sc.created_at,
|
||||
COALESCE(scc.en, ''), COALESCE(scc.tm, ''), COALESCE(scc.ru, '')
|
||||
from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "sc.created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
fmt.Println("=========", err)
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n sub_category.SubCategoryDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Status,
|
||||
&n.Name, &n.CreatedAt,
|
||||
&n.Content.En, &n.Content.Tm, &n.Content.Ru,
|
||||
)
|
||||
if errN != nil {
|
||||
fmt.Println("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.SubCategories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
var (
|
||||
ns sub_category.SubCategoryDTO
|
||||
)
|
||||
|
||||
qC := `select
|
||||
sc.id, sc.category_id, sc.name, sc.status, sc.created_at,
|
||||
COALESCE(scc.en, ''), COALESCE(scc.tm, ''), COALESCE(scc.ru, '')
|
||||
from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id
|
||||
where sc.id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.CatId, &ns.Name, &ns.Status, &ns.CreatedAt,
|
||||
&ns.Content.En, &ns.Content.Tm, &ns.Content.Ru,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req sub_category.AddSubCategoryDTO) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
var (
|
||||
n sub_category.SubCategoryDTO
|
||||
lang sub_category.Language
|
||||
)
|
||||
|
||||
q := `INSERT INTO sub_categories (category_id, name) VALUES ($1, $2) RETURNING id, category_id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.CatId, req.Name).Scan(
|
||||
&n.Id, &n.CatId,
|
||||
&n.Name, &n.Status,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
|
||||
if n.Id != 0 {
|
||||
q = `INSERT INTO sub_categories_content (sub_category_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req sub_category.UpdateSubCategoryDTO, id int) (sub_category.SubCategoryDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n sub_category.SubCategoryDTO
|
||||
lang sub_category.Language
|
||||
)
|
||||
|
||||
q = ` update sub_categories set category_id = $1, name = $2 where Id = $3 RETURNING id, category_id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.CatId, req.Name, id).Scan(
|
||||
&n.Id, &n.CatId,
|
||||
&n.Name, &n.Status,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
|
||||
if n.Id != 0 {
|
||||
q = `UPDATE sub_categories_content SET en = $1, ru = $2, tm = $3
|
||||
WHERE sub_category_id = $4 RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, req.Content.En, req.Content.Ru, req.Content.Tm, n.Id).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
// Row may be missing on older data — insert then.
|
||||
if err.Error() == "no rows in result set" {
|
||||
q = `INSERT INTO sub_categories_content (sub_category_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4) RETURNING en, ru, tm;`
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
}
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateStatusData(ctx context.Context, status string, id int) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
q := ` update sub_categories set status = $1 where id = $2;`
|
||||
|
||||
_, err := r.client.Exec(ctx, q, status, id)
|
||||
|
||||
dt, err := r.GetData(ctx, id)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return dt, err
|
||||
}
|
||||
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, Id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from sub_categories where Id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, Id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
35
backend/internal/admin/sub_category/dto.go
Executable file
35
backend/internal/admin/sub_category/dto.go
Executable file
@@ -0,0 +1,35 @@
|
||||
package sub_category
|
||||
|
||||
import "time"
|
||||
|
||||
type DataDTO struct {
|
||||
SubCategories []SubCategoryDTO `json:"subCategory"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type SubCategoryDTO struct {
|
||||
Id int `json:"Id"`
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
Status bool `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddSubCategoryDTO struct {
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
}
|
||||
|
||||
type UpdateSubCategoryDTO struct {
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
}
|
||||
264
backend/internal/admin/sub_category/handler.go
Executable file
264
backend/internal/admin/sub_category/handler.go
Executable file
@@ -0,0 +1,264 @@
|
||||
package sub_category
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
getEditURL = "/:id/edit"
|
||||
getStatusURL = "/:id/status"
|
||||
)
|
||||
|
||||
var validate *validator.Validate
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getOneURL, h.GetAll)
|
||||
router.GET(getEditURL, h.GetOne)
|
||||
router.POST(getAllURL, h.Create)
|
||||
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.PUT(getStatusURL, h.UpdateStatus)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all sub-categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, status, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Param id path int true "category id"
|
||||
// @Success 200 {object} DataDTO
|
||||
// @Router /admin/sub-categories/{id} [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
categoryId := c.Param("id")
|
||||
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data category
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id}/edit [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create sub categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param sub-categories body AddSubCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddSubCategoryDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
appresult.ErrMissingParam.Err = err
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update sub categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Param sub-categories body UpdateSubCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateSubCategoryDTO
|
||||
res SubCategoryDTO
|
||||
)
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
appresult.ErrNotFound.Err = err
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateStatus godoc
|
||||
// @Description update status sub-categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Param status query bool true "status"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id}/status [put]
|
||||
func (h *handler) UpdateStatus(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
res SubCategoryDTO
|
||||
)
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
status, _ := c.GetQuery("status")
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateStatusData(context.Background(), status, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete sub-category
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub category id"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/sub-categories/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/sub_category/model.go
Executable file
1
backend/internal/admin/sub_category/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package sub_category
|
||||
15
backend/internal/admin/sub_category/storage.go
Executable file
15
backend/internal/admin/sub_category/storage.go
Executable file
@@ -0,0 +1,15 @@
|
||||
package sub_category
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params, categoryId int) (DataDTO, error)
|
||||
GetData(ctx context.Context, id int) (SubCategoryDTO, error)
|
||||
AddData(ctx context.Context, dto AddSubCategoryDTO) (SubCategoryDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateSubCategoryDTO, id int) (SubCategoryDTO, error)
|
||||
UpdateStatusData(ctx context.Context, status string, id int) (SubCategoryDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
104
backend/internal/admin/ui/handler.go
Normal file
104
backend/internal/admin/ui/handler.go
Normal file
@@ -0,0 +1,104 @@
|
||||
// Package ui serves the admin dashboard pages at /admin.
|
||||
// Pages are template shells; all data is fetched client-side from the
|
||||
// existing JWT-protected /v1/admin API.
|
||||
package ui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Resource describes an admin CRUD resource rendered by the generic
|
||||
// list/form templates. Slug is both the URL segment and the key used by
|
||||
// the client-side schema in resources.js.
|
||||
type Resource struct {
|
||||
Slug string
|
||||
Title string
|
||||
}
|
||||
|
||||
var resources = []Resource{
|
||||
{Slug: "categories", Title: "Categories"},
|
||||
{Slug: "sub-categories", Title: "Sub-categories"},
|
||||
{Slug: "banners", Title: "Banners"},
|
||||
{Slug: "news", Title: "News"},
|
||||
{Slug: "static", Title: "Static pages"},
|
||||
{Slug: "currency", Title: "Currency rates"},
|
||||
}
|
||||
|
||||
// Register mounts templates, static assets and all dashboard page routes.
|
||||
func Register(router *gin.Engine) {
|
||||
router.LoadHTMLGlob("web/admin/templates/**/*.html")
|
||||
router.Static("/admin/assets", "./web/admin/assets")
|
||||
|
||||
admin := router.Group("/admin")
|
||||
|
||||
admin.GET("/login", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/login", gin.H{
|
||||
"Title": "Login",
|
||||
"Page": "login",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/dashboard", gin.H{
|
||||
"Title": "Dashboard",
|
||||
"Page": "dashboard",
|
||||
"Active": "dashboard",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/settings", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/settings", gin.H{
|
||||
"Title": "Settings",
|
||||
"Page": "settings",
|
||||
"Active": "settings",
|
||||
})
|
||||
})
|
||||
|
||||
for _, res := range resources {
|
||||
res := res
|
||||
|
||||
admin.GET("/"+res.Slug, func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/list", gin.H{
|
||||
"Title": res.Title,
|
||||
"Page": "list",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/"+res.Slug+"/new", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/form", gin.H{
|
||||
"Title": "New — " + res.Title,
|
||||
"Page": "form",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
"Mode": "create",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/"+res.Slug+"/:id/edit", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/form", gin.H{
|
||||
"Title": "Edit — " + res.Title,
|
||||
"Page": "form",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
"Mode": "edit",
|
||||
"Id": c.Param("id"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
router.NoRoute(func(c *gin.Context) {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/admin") {
|
||||
c.HTML(http.StatusNotFound, "pages/404", gin.H{
|
||||
"Title": "Page not found",
|
||||
"Page": "404",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusNotFound, gin.H{"status": false, "message": "not found"})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user