fixed
This commit is contained in:
1 parent
4194cef934
commit
363127fe9e
3350 files changed
+1284220
-1
No files matched your search
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Executable
+88
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Executable
+29
@@ -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"`
|
||||
}
|
||||
Executable
+320
@@ -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
|
||||
}
|
||||
Executable
+9
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+48
@@ -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"`
|
||||
}
|
||||
Executable
+212
@@ -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
|
||||
}
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
package banner
|
||||
Executable
+14
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+49
@@ -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"`
|
||||
}
|
||||
Executable
+246
@@ -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
|
||||
}
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
package category
|
||||
Executable
+16
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Executable
+201
@@ -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
|
||||
}
|
||||
Executable
+36
@@ -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"`
|
||||
}
|
||||
Executable
+177
@@ -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)
|
||||
}
|
||||
Executable
+14
@@ -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
@@ -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)
|
||||
}
|
||||
Executable
+20
@@ -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"`
|
||||
}
|
||||
Executable
+94
@@ -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)
|
||||
}
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
package setting
|
||||
Executable
+8
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+35
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
package sub_category
|
||||
+15
@@ -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
|
||||
}
|
||||
@@ -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"})
|
||||
})
|
||||
}
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
package appresult
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
var (
|
||||
ErrMissingParam = NewAppError(nil, "missing param", "SE-00001")
|
||||
ErrNotFound = NewAppError(nil, "not found", "SE-00003")
|
||||
ErrInternalServer = NewAppError(nil, "internal server error", "SE-00004")
|
||||
ErrNotAcceptable = NewAppError(nil, "Not acceptable", "SE-00007")
|
||||
ErrCheckPasswordLimitFull = NewAppError(nil, "ErrCheckPasswordLimitFull", "SE-00008")
|
||||
ErrUpdatePassword = NewAppError(nil, "missing password", "SE-00010")
|
||||
ErrCheckEmail = NewAppError(nil, "Please enter a valid email address", "SE-00011")
|
||||
ErrAccount = NewAppError(nil, "This account has already been registered", "SE-00015")
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
Status bool `json:"status"`
|
||||
Err error `json:"err,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (e *AppError) Unwrap() error { return e.Err }
|
||||
|
||||
func (e *AppError) Marshal() []byte {
|
||||
marshal, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return marshal
|
||||
}
|
||||
|
||||
func NewAppError(err error, message, code string) *AppError {
|
||||
return &AppError{
|
||||
Status: false,
|
||||
Err: err,
|
||||
Message: message,
|
||||
Code: code,
|
||||
}
|
||||
}
|
||||
|
||||
func systemError(err error) *AppError {
|
||||
return NewAppError(err, "internal system error", "SE-000")
|
||||
}
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
package appresult
|
||||
|
||||
import (
|
||||
"bankline/internal/config"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UnsignedResponse struct {
|
||||
Message interface{} `json:"message"`
|
||||
}
|
||||
|
||||
type appHandler func(w http.ResponseWriter, r *http.Request) error
|
||||
|
||||
func HeaderContentTypeJson() (string, string) {
|
||||
return "Content-Type", "application/json"
|
||||
}
|
||||
func AccessControlAllow() (string, string) {
|
||||
return "Access-Control-Allow-Origin", "*"
|
||||
}
|
||||
|
||||
func respondWithError(c *gin.Context, code int, message interface{}) {
|
||||
c.AbortWithStatusJSON(code, gin.H{"error": message})
|
||||
}
|
||||
|
||||
func JwtTokenCheck() gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
token := c.GetHeader("Authorization")
|
||||
|
||||
if token == "" {
|
||||
respondWithError(c, 403, "Authorization header is missing")
|
||||
return
|
||||
}
|
||||
|
||||
cfg := config.GetConfig()
|
||||
claims, err := TokenClaims(token, cfg.JwtKey)
|
||||
if err != nil {
|
||||
respondWithError(c, 401, "Token is expired")
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin := claims["admin"].(bool)
|
||||
if isAdmin == false {
|
||||
respondWithError(c, 403, "Unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("id", fmt.Sprint(claims["id"]))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func TokenClaims(token, secretKey string) (jwt.MapClaims, error) {
|
||||
decoded, err := jwt.Parse(token, 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(secretKey), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := decoded.Claims.(jwt.MapClaims)
|
||||
|
||||
if !ok {
|
||||
// TODO tokenin omrini test etmeli
|
||||
return nil, ErrInternalServer
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
package appresult
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
var (
|
||||
Success = NewAppSuccess("Success !!!", "SS-10000", nil)
|
||||
SuccessRegister = NewAppSuccess("You don't have an account.Please sign up", "SS-11000", nil)
|
||||
SuccessLogin = NewAppSuccess("you have an account !!!", "SS-12000", nil)
|
||||
)
|
||||
|
||||
type AppSuccess struct {
|
||||
Status bool `json:"status"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Error() string {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Success() string {
|
||||
return s.Message
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Marshal() []byte {
|
||||
marshal, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return marshal
|
||||
}
|
||||
|
||||
func NewAppSuccess(message, code string, data interface{}) *AppSuccess {
|
||||
return &AppSuccess{
|
||||
Status: true,
|
||||
Message: message,
|
||||
Code: code,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/client/users"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) users.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r repository) GetNews(ctx context.Context, limit, page int) (users.DataNewsDTO, error) {
|
||||
|
||||
var dt users.DataNewsDTO
|
||||
|
||||
qC := `select count(*) from news;`
|
||||
if err := r.client.QueryRow(ctx, qC).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
|
||||
ORDER BY n.date_release DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ns := []users.NewsDTO{}
|
||||
for rows.Next() {
|
||||
var n users.NewsDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En, &n.Content.Tm, &n.Content.Ru,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.News = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetCategories(ctx context.Context) ([]users.CategoryDTO, error) {
|
||||
|
||||
q := ` SELECT
|
||||
c.id, c.name, c.img,
|
||||
COALESCE(
|
||||
jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'id', sc.id, 'categoryId', sc.category_id,
|
||||
'name', sc.name, 'count', sc.count,
|
||||
'content', jsonb_build_object(
|
||||
'en', COALESCE(scc.en, ''),
|
||||
'ru', COALESCE(scc.ru, ''),
|
||||
'tm', COALESCE(scc.tm, '')
|
||||
)
|
||||
)
|
||||
ORDER BY sc.created_at DESC
|
||||
) FILTER (WHERE sc.id IS NOT NULL AND sc.status = true),
|
||||
'[]'
|
||||
) AS sub_categories
|
||||
FROM categories c
|
||||
LEFT JOIN sub_categories sc ON sc.category_id = c.id
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id
|
||||
WHERE c.status = true
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at ASC;`
|
||||
|
||||
rows, err := r.client.Query(ctx, q)
|
||||
if err != nil {
|
||||
r.logger.Error("get categories :::", err)
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
cs := []users.CategoryDTO{}
|
||||
for rows.Next() {
|
||||
var c users.CategoryDTO
|
||||
errC := rows.Scan(
|
||||
&c.Id, &c.Name, &c.Image,
|
||||
&c.SubCategories,
|
||||
)
|
||||
if errC != nil {
|
||||
r.logger.Error("errC :::", errC)
|
||||
continue
|
||||
}
|
||||
|
||||
cs = append(cs, c)
|
||||
}
|
||||
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
func (r repository) GetBanners(ctx context.Context, limit, page int) (users.DataBannerDTO, error) {
|
||||
|
||||
var dt users.DataBannerDTO
|
||||
|
||||
qC := `select count(*) from banner;`
|
||||
if err := r.client.QueryRow(ctx, qC).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count banners :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
FROM banner
|
||||
ORDER BY created_at DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get banners :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
bs := []users.BannerDTO{}
|
||||
for rows.Next() {
|
||||
var b users.BannerDTO
|
||||
errB := rows.Scan(
|
||||
&b.Id, &b.Title,
|
||||
&b.ContentTm, &b.ContentRu, &b.ContentEn,
|
||||
&b.Image, &b.CreatedAt,
|
||||
)
|
||||
if errB != nil {
|
||||
r.logger.Error("errB :::", errB)
|
||||
continue
|
||||
}
|
||||
|
||||
bs = append(bs, b)
|
||||
}
|
||||
dt.Banners = bs
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetStatics(ctx context.Context, limit, page int) (users.DataStaticDTO, error) {
|
||||
|
||||
var dt users.DataStaticDTO
|
||||
|
||||
qC := `select count(*) from static;`
|
||||
if err := r.client.QueryRow(ctx, qC).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count statics :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
FROM static
|
||||
ORDER BY created_at DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get statics :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ss := []users.StaticDTO{}
|
||||
for rows.Next() {
|
||||
var s users.StaticDTO
|
||||
errS := rows.Scan(
|
||||
&s.Id, &s.Logo, &s.Title,
|
||||
&s.ContentTm, &s.ContentRu, &s.ContentEn,
|
||||
&s.CreatedAt,
|
||||
)
|
||||
if errS != nil {
|
||||
r.logger.Error("errS :::", errS)
|
||||
continue
|
||||
}
|
||||
|
||||
ss = append(ss, s)
|
||||
}
|
||||
dt.Statics = ss
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetStaticById(ctx context.Context, id int) (users.StaticDTO, error) {
|
||||
var s users.StaticDTO
|
||||
|
||||
q := ` SELECT
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
FROM static
|
||||
WHERE id = $1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&s.Id, &s.Logo, &s.Title,
|
||||
&s.ContentTm, &s.ContentRu, &s.ContentEn,
|
||||
&s.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r repository) GetCurrency(ctx context.Context) (users.CurrencyDTO, error) {
|
||||
var cu users.CurrencyDTO
|
||||
|
||||
q := ` SELECT
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
path, created_at
|
||||
FROM currency
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q).Scan(
|
||||
&cu.Id, &cu.Title,
|
||||
&cu.Content.Tm, &cu.Content.Ru, &cu.Content.En,
|
||||
&cu.Path, &cu.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return cu, err
|
||||
}
|
||||
return cu, nil
|
||||
}
|
||||
|
||||
func (r repository) GetSetting(ctx context.Context) (users.SettingDTO, error) {
|
||||
var s users.SettingDTO
|
||||
|
||||
q := ` SELECT
|
||||
uuid::text, logo_r, phone_number, fax_number, help_number, created_at
|
||||
FROM setting
|
||||
ORDER BY id ASC
|
||||
LIMIT 1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q).Scan(
|
||||
&s.UUID, &s.LogoR, &s.PhoneNumber, &s.FaxNumber, &s.HelpNumber, &s.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r repository) GetSubCategoryById(ctx context.Context, id int) (users.SubCategoryDTO, error) {
|
||||
var sc users.SubCategoryDTO
|
||||
|
||||
q := ` SELECT
|
||||
sc.id, sc.category_id,
|
||||
sc.name, sc.count,
|
||||
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 AND sc.status = true;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&sc.Id, &sc.CategoryId,
|
||||
&sc.Name, &sc.Count,
|
||||
&sc.Content.En, &sc.Content.Tm, &sc.Content.Ru,
|
||||
)
|
||||
if err != nil {
|
||||
return sc, err
|
||||
}
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
func (r repository) GetNewsById(ctx context.Context, id int) (users.NewsDTO, error) {
|
||||
var n users.NewsDTO
|
||||
|
||||
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
|
||||
}
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
package users
|
||||
|
||||
import "time"
|
||||
|
||||
type DataNewsDTO struct {
|
||||
News []NewsDTO `json:"news"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type NewsDTO struct {
|
||||
Id int `json:"id"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type CategoryDTO struct {
|
||||
Id int `json:"id"`
|
||||
Name Language `json:"name"`
|
||||
Image string `json:"imagePath"`
|
||||
SubCategories []SubCategoryDTO `json:"subCategories"`
|
||||
}
|
||||
|
||||
type SubCategoryDTO struct {
|
||||
Id int `json:"id"`
|
||||
CategoryId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type DataBannerDTO struct {
|
||||
Banners []BannerDTO `json:"banners"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type BannerDTO 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 DataStaticDTO struct {
|
||||
Statics []StaticDTO `json:"statics"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
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 CurrencyDTO struct {
|
||||
Id int `json:"id"`
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Path string `json:"path"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type SettingDTO struct {
|
||||
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"`
|
||||
}
|
||||
Executable
+265
@@ -0,0 +1,265 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getNewsURL = "/news"
|
||||
getOneNewsURL = "/news/:id"
|
||||
getCategoriesURL = "/categories"
|
||||
getOneSubCategoryURL = "/sub-categories/:id"
|
||||
getBannersURL = "/banners"
|
||||
getStaticsURL = "/static"
|
||||
getOneStaticURL = "/static/:id"
|
||||
getCurrencyURL = "/currency"
|
||||
getSettingURL = "/setting"
|
||||
)
|
||||
|
||||
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.GET(getNewsURL, h.GetNews)
|
||||
router.GET(getOneNewsURL, h.GetOneNews)
|
||||
router.GET(getCategoriesURL, h.GetCategories)
|
||||
router.GET(getOneSubCategoryURL, h.GetSubCategory)
|
||||
router.GET(getBannersURL, h.GetBanners)
|
||||
router.GET(getStaticsURL, h.GetStatics)
|
||||
router.GET(getOneStaticURL, h.GetOneStatic)
|
||||
router.GET(getCurrencyURL, h.GetCurrency)
|
||||
router.GET(getSettingURL, h.GetSetting)
|
||||
}
|
||||
|
||||
// =================================================================================
|
||||
|
||||
// GetNews godoc
|
||||
// @Description all news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataNewsDTO
|
||||
// @Router /client/users/news [get]
|
||||
func (h *handler) GetNews(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetNews(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOneNews godoc
|
||||
// @Description news by id
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {object} NewsDTO
|
||||
// @Router /client/users/news/{id} [get]
|
||||
func (h *handler) GetOneNews(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetNewsById(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)
|
||||
}
|
||||
|
||||
// GetSubCategory godoc
|
||||
// @Description sub-category by id
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "sub-category ID"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /client/users/sub-categories/{id} [get]
|
||||
func (h *handler) GetSubCategory(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetSubCategoryById(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)
|
||||
}
|
||||
|
||||
// GetBanners godoc
|
||||
// @Description all banners
|
||||
// @Tags banners
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataBannerDTO
|
||||
// @Router /client/users/banners [get]
|
||||
func (h *handler) GetBanners(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetBanners(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetStatics godoc
|
||||
// @Description all static data
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataStaticDTO
|
||||
// @Router /client/users/static [get]
|
||||
func (h *handler) GetStatics(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetStatics(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOneStatic godoc
|
||||
// @Description static data by id
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {object} StaticDTO
|
||||
// @Router /client/users/static/{id} [get]
|
||||
func (h *handler) GetOneStatic(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetStaticById(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)
|
||||
}
|
||||
|
||||
// GetCurrency godoc
|
||||
// @Description latest currency content (title + HTML table per language)
|
||||
// @Tags currency
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Router /client/users/currency [get]
|
||||
func (h *handler) GetCurrency(c *gin.Context) {
|
||||
result, err := h.repository.GetCurrency(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetSetting godoc
|
||||
// @Description site setting (logo and contact numbers)
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /client/users/setting [get]
|
||||
func (h *handler) GetSetting(c *gin.Context) {
|
||||
result, err := h.repository.GetSetting(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetCategories godoc
|
||||
// @Description all active categories with their active subcategories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} CategoryDTO
|
||||
// @Router /client/users/categories [get]
|
||||
func (h *handler) GetCategories(c *gin.Context) {
|
||||
result, err := h.repository.GetCategories(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
package users
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
GetNews(ctx context.Context, limit, page int) (DataNewsDTO, error)
|
||||
GetNewsById(ctx context.Context, id int) (NewsDTO, error)
|
||||
|
||||
GetCategories(ctx context.Context) ([]CategoryDTO, error)
|
||||
GetSubCategoryById(ctx context.Context, id int) (SubCategoryDTO, error)
|
||||
|
||||
GetBanners(ctx context.Context, limit, page int) (DataBannerDTO, error)
|
||||
|
||||
GetStatics(ctx context.Context, limit, page int) (DataStaticDTO, error)
|
||||
GetStaticById(ctx context.Context, id int) (StaticDTO, error)
|
||||
|
||||
GetCurrency(ctx context.Context) (CurrencyDTO, error)
|
||||
GetSetting(ctx context.Context) (SettingDTO, error)
|
||||
}
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bankline/pkg/logging"
|
||||
"sync"
|
||||
|
||||
"github.com/ilyakaznacheev/cleanenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
IsDebug *bool `yaml:"is_debug" env-required:"true"`
|
||||
Listen struct {
|
||||
Type string `yaml:"type" env-default:"port"`
|
||||
BindIP string `yaml:"bind_ip" env-default:"0.0.0.0"`
|
||||
Port string `yaml:"port" env-default:"8080"`
|
||||
} `yaml:"listen"`
|
||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||
Storage StorageConfig `yaml:"storage"`
|
||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||
AppVersion string `yaml:"app_version" env-required:"true"`
|
||||
}
|
||||
|
||||
type StorageConfig struct {
|
||||
PgPoolMaxConn int `yaml:"pg_pool_max_conn" env-required:"true"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
Database string `json:"database"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
var instance *Config
|
||||
var once sync.Once
|
||||
|
||||
func GetConfig() *Config {
|
||||
once.Do(func() {
|
||||
|
||||
pathConfig := "./config.yaml"
|
||||
logger := logging.GetLogger()
|
||||
logger.Info("read application configuration")
|
||||
instance = &Config{}
|
||||
if err := cleanenv.ReadConfig(pathConfig, instance); err != nil {
|
||||
help, _ := cleanenv.GetDescription(instance, nil)
|
||||
logger.Info(help)
|
||||
logger.Fatal(err)
|
||||
}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
Register(router *gin.RouterGroup)
|
||||
}
|
||||
Executable
+119
@@ -0,0 +1,119 @@
|
||||
package handlermanager
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
authdb "bankline/internal/admin/auth/db"
|
||||
"bankline/internal/admin/banner"
|
||||
bannerdb "bankline/internal/admin/banner/db"
|
||||
"bankline/internal/admin/category"
|
||||
catdb "bankline/internal/admin/category/db"
|
||||
"bankline/internal/admin/currency"
|
||||
currencydb "bankline/internal/admin/currency/db"
|
||||
"bankline/internal/admin/news"
|
||||
newsdb "bankline/internal/admin/news/db"
|
||||
"bankline/internal/admin/setting"
|
||||
settingdb "bankline/internal/admin/setting/db"
|
||||
"bankline/internal/admin/static"
|
||||
staticdb "bankline/internal/admin/static/db"
|
||||
"bankline/internal/admin/sub_category"
|
||||
subcategorydb "bankline/internal/admin/sub_category/db"
|
||||
adminui "bankline/internal/admin/ui"
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/client/users"
|
||||
usersdb "bankline/internal/client/users/db"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/swaggo/swag"
|
||||
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
const (
|
||||
authURL = "/v1/admin"
|
||||
|
||||
categoryURL = "/v1/admin/categories"
|
||||
subCategoryURL = "/v1/admin/sub-categories"
|
||||
settingURL = "/v1/admin/setting"
|
||||
bannerURL = "/v1/admin/banner"
|
||||
newsURL = "/v1/admin/news"
|
||||
staticURL = "/v1/admin/static"
|
||||
currencyURL = "/v1/admin/currency"
|
||||
|
||||
usersURL = "/v1/client/users"
|
||||
)
|
||||
|
||||
func Manager(client *pgxpool.Pool, logger *logging.Logger) *gin.Engine {
|
||||
|
||||
router := gin.Default()
|
||||
|
||||
router.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", http.MethodGet, http.MethodPatch, http.MethodPost},
|
||||
AllowHeaders: []string{
|
||||
"Content-Type", "Content-Length", "Accept-Encoding",
|
||||
"Authorization", "Cache-Control",
|
||||
"access-control-allow-origin", "access-control-allow-headers",
|
||||
},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: true,
|
||||
}))
|
||||
|
||||
authRouterManager := router.Group(authURL)
|
||||
authRepository := authdb.NewRepository(client, logger)
|
||||
authRouterHandler := auth.NewHandler(logger, authRepository)
|
||||
authRouterHandler.Register(authRouterManager)
|
||||
|
||||
categoryRouterManager := router.Group(categoryURL)
|
||||
categoryRouterManager.Use(appresult.JwtTokenCheck())
|
||||
categoryRepository := catdb.NewRepository(client, logger)
|
||||
categoryRouterHandler := category.NewHandler(categoryRepository, logger)
|
||||
categoryRouterHandler.Register(categoryRouterManager)
|
||||
|
||||
subCategoryRouterManager := router.Group(subCategoryURL)
|
||||
subCategoryRouterManager.Use(appresult.JwtTokenCheck())
|
||||
subCategoryRepository := subcategorydb.NewRepository(client, logger)
|
||||
subCategoryRouterHandler := sub_category.NewHandler(subCategoryRepository, logger)
|
||||
subCategoryRouterHandler.Register(subCategoryRouterManager)
|
||||
|
||||
settingRouterManager := router.Group(settingURL)
|
||||
settingRouterManager.Use(appresult.JwtTokenCheck())
|
||||
settingRepository := settingdb.NewRepository(client, logger)
|
||||
settingRouterHandler := setting.NewHandler(settingRepository, logger)
|
||||
settingRouterHandler.Register(settingRouterManager)
|
||||
|
||||
bannerRouterManager := router.Group(bannerURL)
|
||||
bannerRouterManager.Use(appresult.JwtTokenCheck())
|
||||
bannerRepository := bannerdb.NewRepository(client, logger)
|
||||
bannerRouterHandler := banner.NewHandler(bannerRepository, logger)
|
||||
bannerRouterHandler.Register(bannerRouterManager)
|
||||
|
||||
newsRouterManager := router.Group(newsURL)
|
||||
newsRouterManager.Use(appresult.JwtTokenCheck())
|
||||
newsRepository := newsdb.NewRepository(client, logger)
|
||||
newsRouterHandler := news.NewHandler(newsRepository, logger)
|
||||
newsRouterHandler.Register(newsRouterManager)
|
||||
|
||||
staticRouterManager := router.Group(staticURL)
|
||||
staticRouterManager.Use(appresult.JwtTokenCheck())
|
||||
staticRepository := staticdb.NewRepository(client, logger)
|
||||
staticRouterHandler := static.NewHandler(staticRepository, logger)
|
||||
staticRouterHandler.Register(staticRouterManager)
|
||||
|
||||
currencyRouterManager := router.Group(currencyURL)
|
||||
currencyRouterManager.Use(appresult.JwtTokenCheck())
|
||||
currencyRepository := currencydb.NewRepository(client, logger)
|
||||
currencyRouterHandler := currency.NewHandler(currencyRepository, logger)
|
||||
currencyRouterHandler.Register(currencyRouterManager)
|
||||
|
||||
usersRouterManager := router.Group(usersURL)
|
||||
usersRepository := usersdb.NewRepository(client, logger)
|
||||
usersRouterHandler := users.NewHandler(logger, usersRepository)
|
||||
usersRouterHandler.Register(usersRouterManager)
|
||||
|
||||
adminui.Register(router)
|
||||
|
||||
return router
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Package listing provides common query parameters for admin list endpoints:
|
||||
// pagination, search and sorting.
|
||||
package listing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Params holds common list query options.
|
||||
type Params struct {
|
||||
Limit int
|
||||
Page int
|
||||
Search string
|
||||
Sort string
|
||||
Order string
|
||||
}
|
||||
|
||||
// FromQuery extracts list params from the request query string.
|
||||
func FromQuery(c *gin.Context) Params {
|
||||
limit, _ := strconv.Atoi(c.Query("limit"))
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
return Params{
|
||||
Limit: limit,
|
||||
Page: page,
|
||||
Search: strings.TrimSpace(c.Query("search")),
|
||||
Sort: c.Query("sort"),
|
||||
Order: strings.ToLower(c.Query("order")),
|
||||
}
|
||||
}
|
||||
|
||||
// Paginated reports whether pagination should be applied.
|
||||
// Mirrors the pre-existing behaviour: limit=0 or page=0 returns all rows.
|
||||
func (p Params) Paginated() bool { return p.Limit > 0 && p.Page > 0 }
|
||||
|
||||
// Offset returns the SQL offset for the current page.
|
||||
func (p Params) Offset() int { return (p.Page - 1) * p.Limit }
|
||||
|
||||
// SearchPattern returns an ILIKE pattern for the search term.
|
||||
func (p Params) SearchPattern() string { return "%" + p.Search + "%" }
|
||||
|
||||
// OrderClause returns a safe ORDER BY clause. The requested sort key is looked
|
||||
// up in the whitelist map (query key -> SQL column); unknown or empty keys fall
|
||||
// back to the def expression. User input is never interpolated directly.
|
||||
func (p Params) OrderClause(whitelist map[string]string, def string) string {
|
||||
col, ok := whitelist[p.Sort]
|
||||
if !ok {
|
||||
return " ORDER BY " + def + " "
|
||||
}
|
||||
dir := "DESC"
|
||||
if p.Order == "asc" {
|
||||
dir = "ASC"
|
||||
}
|
||||
return fmt.Sprintf(" ORDER BY %s %s ", col, dir)
|
||||
}
|
||||
Reference in new issue
Block a user