Add client banner-by-id API and point frontend at new client endpoints.

Also save admin uploads locally under /public/images with a 10MB limit.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-05 14:46:23 +05:00
parent a3c87d231b
commit ca0692d190
5 changed files with 144 additions and 98 deletions

View File

@@ -143,6 +143,8 @@ func (h *handler) getProfile(c *gin.Context) {
// @Router /admin/file [post]
func (h *handler) fileUpload(c *gin.Context) {
const maxUploadBytes = 10 << 20 // 10 MB
file, header, err := c.Request.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, "get form err: %s", err.Error())
@@ -156,42 +158,56 @@ func (h *handler) fileUpload(c *gin.Context) {
}
}(file)
if header.Size > maxUploadBytes {
c.JSON(http.StatusBadRequest, gin.H{"error": "file size must not exceed 10 MB"})
return
}
cfg := config.GetConfig()
appDirPath := cfg.PublicFilePath + "/images/"
err = os.MkdirAll(appDirPath, os.ModePerm)
if err != nil {
fmt.Println("wwwww", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create upload directory"})
return
}
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
dbPath := "/images/" + appName
dbPath := "/public/images/" + appName
localPath := appDirPath + appName
minioClient, err := minioUpload.ConnectionMinio()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
if err := c.SaveUploadedFile(header, localPath); err != nil {
fmt.Println("Error saving file to public/images:", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "File upload 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
}
// 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

View File

@@ -180,6 +180,27 @@ func (r repository) GetBanners(ctx context.Context, limit, page int) (users.Data
return dt, nil
}
func (r repository) GetBannerById(ctx context.Context, id int) (users.BannerDTO, error) {
var b users.BannerDTO
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(
&b.Id, &b.Title,
&b.ContentTm, &b.ContentRu, &b.ContentEn,
&b.Image, &b.CreatedAt,
)
if err != nil {
return b, err
}
return b, nil
}
func (r repository) GetStatics(ctx context.Context, limit, page int) (users.DataStaticDTO, error) {
var dt users.DataStaticDTO

View File

@@ -16,6 +16,7 @@ const (
getCategoriesURL = "/categories"
getOneSubCategoryURL = "/sub-categories/:id"
getBannersURL = "/banners"
getOneBannerURL = "/banners/:id"
getStaticsURL = "/static"
getOneStaticURL = "/static/:id"
getCurrencyURL = "/currency"
@@ -40,6 +41,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
router.GET(getCategoriesURL, h.GetCategories)
router.GET(getOneSubCategoryURL, h.GetSubCategory)
router.GET(getBannersURL, h.GetBanners)
router.GET(getOneBannerURL, h.GetOneBanner)
router.GET(getStaticsURL, h.GetStatics)
router.GET(getOneStaticURL, h.GetOneStatic)
router.GET(getCurrencyURL, h.GetCurrency)
@@ -154,6 +156,32 @@ func (h *handler) GetBanners(c *gin.Context) {
c.JSON(http.StatusOK, successResult)
}
// GetOneBanner godoc
// @Description banner by id
// @Tags banners
// @Accept json
// @Produce json
// @Param id path int true "banner ID"
// @Success 200 {object} BannerDTO
// @Router /client/users/banners/{id} [get]
func (h *handler) GetOneBanner(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
return
}
result, err := h.repository.GetBannerById(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)
}
// GetStatics godoc
// @Description all static data
// @Tags statics

View File

@@ -10,6 +10,7 @@ type Repository interface {
GetSubCategoryById(ctx context.Context, id int) (SubCategoryDTO, error)
GetBanners(ctx context.Context, limit, page int) (DataBannerDTO, error)
GetBannerById(ctx context.Context, id int) (BannerDTO, error)
GetStatics(ctx context.Context, limit, page int) (DataStaticDTO, error)
GetStaticById(ctx context.Context, id int) (StaticDTO, error)

View File

@@ -26,21 +26,29 @@ function removeByClassName(className) {
}
function baseUrl() {
return 'https://tbbank.gov.tm';
return 'http://216.250.10.141';
}
function postData(url = '', data = {}) {
function getData(url = '') {
return fetch(baseUrl() + url, {
method: 'POST',
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
'Accept': 'application/json'
}
})
.then(response => response.json());
}
function localizedContent(item) {
if (window.locale === 'ru') {
return item.contentRu
}
if (window.locale === 'en') {
return item.contentEn
}
return item.contentTm
}
function getCurrentLang()
{
return window.location.search.includes('lang=ru') ? 'ru' : '';
@@ -89,8 +97,7 @@ function setTranslations() {
function fetchPhoneNumbers()
{
fetch(baseUrl() + '/api/v1/setting/get')
.then(response => response.json())
getData('/api/v1/client/users/setting')
.then(response => {
if (! response.status) {
return;
@@ -120,20 +127,18 @@ async function fetchMenuItems() {
const container = $_ID('menu-items-container')
const sideBarMenuItems = $_ID('sidebar-menu-items')
const response = await postData('/api/v1/category/get-no-content')
const response = await getData('/api/v1/client/users/categories')
response.data.forEach(menuItem => {
let subcategoriesTemplate = '';
if (menuItem.subCat && menuItem.subCat.length > 0 ) {
menuItem.subCat.forEach(subcategory => {
if (subcategory.UUID && subcategory.name) {
if (menuItem.subCategories && menuItem.subCategories.length > 0 ) {
menuItem.subCategories.forEach(subcategory => {
if (subcategory.id && subcategory.name) {
subcategoriesTemplate += `
<li>
<a class="bg-trasparent lg:bg-white" href="${
(subcategory.link || subcategory.pdf)
? subcategory.link ? subcategory.link : subcategory.pdf
: '/page.html?uuid=' + subcategory.UUID + '&lang=' + getCurrentLang()
'/page.html?id=' + subcategory.id + '&lang=' + getCurrentLang()
}">
${subcategory.name[window.locale]}
</a>
@@ -181,21 +186,21 @@ async function fetchMenuItems() {
async function fetchSliders() {
const imageSliderContainer = $_ID('slider-images-container')
const response = await postData('/api/v1/main_slider/get-all')
const response = await getData('/api/v1/client/users/banners')
removeByClassName('homepage-slider-loader')
response.data.forEach(slider => {
response.data.banners.forEach(slider => {
imageSliderContainer.insertAdjacentHTML('beforeend', `
<swiper-slide>
<a href="${
slider.UUID
? `/banner.html?uuid=${slider.UUID}` + '&lang=' + getCurrentLang()
slider.id
? `/banner.html?id=${slider.id}` + '&lang=' + getCurrentLang()
: ''
}">
<img
src="${baseUrl() + slider.slider}"
src="${baseUrl() + slider.imagePath}"
class="mx-auto w-fit cursor-pointer" alt="slider"
>
</a>
@@ -207,44 +212,21 @@ async function fetchSliders() {
}
async function fetchMiniSliders() {
const imageSliderContainer = $_ID('mini-slider')
const dotsContainer = $_ID('mini-slider-dots-container')
const response = await postData('/api/v1/mini_slider/get-all')
removeByClassName('minislider-loader')
let count = 0;
response.data.forEach(slider => {
count++;
imageSliderContainer.insertAdjacentHTML('beforeend', `
<div class="mySlides fade w-full relative">
<div class="numbertext"></div>
<img class="w-full" src="${baseUrl() + slider.path}" loading="lazy">
<div
class="text mb-5 py-5 px-3 text-white text-2xl"
style="background-color: rgba(0, 0, 0, .75)"
>${slider.title['tm']}</div>
</div>
`)
})
initializeMiniSlider()
}
async function fetchMiniCategories() {
const miniCategoryContainer = $_ID('mini-category-content-container')
const response = await postData('/api/v1/mini_category/get-all')
const response = await getData('/api/v1/client/users/static')
removeByClassName('mini-categories-loader')
response.data.forEach(category => {
response.data.statics.forEach(category => {
miniCategoryContainer.insertAdjacentHTML('beforeend', `
<a href="/action.html?uuid=${category.UUID + '&lang=' + getCurrentLang()}">
<a href="/action.html?id=${category.id + '&lang=' + getCurrentLang()}">
<div class="bg-gray-100 flex flex-1 flex-col items-center gap-3 py-7 px-3 mt-2 rounded-md">
<img src="${baseUrl() + category.path}" class="w-16 h-16" alt="..." loading="lazy">
<img src="${baseUrl() + category.logo}" class="w-16 h-16" alt="..." loading="lazy">
<h1 class="text-gray-700 uppercase text-center">${category.title[window.locale]}</h1>
</div>
</a>
@@ -254,7 +236,7 @@ async function fetchMiniCategories() {
async function fetchCurrencies() {
const currencyTable = $_ID('currency-table')
const response = await postData('/api/v1/currency/get')
const response = await getData('/api/v1/client/users/currency')
removeByClassName('currency-table-loader')
currencyTable.innerHTML = response.data.content[window.locale];
@@ -277,11 +259,11 @@ async function fetchCurrencies() {
async function fetchNews() {
const newsContainer = $_ID('news-content-container')
const response = await postData('/api/v1/news/get-all')
const response = await getData('/api/v1/client/users/news')
removeByClassName('news-loaders')
let count = 0;
response.data.forEach(news => {
response.data.news.forEach(news => {
count++;
if (count > 6) {
@@ -289,10 +271,10 @@ async function fetchNews() {
}
newsContainer.insertAdjacentHTML('beforeend', `
<a href="news.html?uuid=${news.UUID + '&lang=' + getCurrentLang()}">
<a href="news.html?id=${news.id + '&lang=' + getCurrentLang()}">
<div class="flex flex-col px-3 mt-3">
<div class="h-60">
<img src="${baseUrl() + news.path}" class="news-img-size" alt="..." loading="lazy">
<img src="${baseUrl() + news.imagePath}" class="news-img-size" alt="..." loading="lazy">
</div>
<h1 class="text-base text-gray-800 mt-2 py-2 px-1 text-center">${news.title[window.locale]}</h1>
</div>
@@ -304,15 +286,13 @@ async function fetchNews() {
async function fetchSubCategory() {
const pageURL = new URL(location);
if (! pageURL.searchParams.has('uuid')) {
if (! pageURL.searchParams.has('id')) {
return;
}
const pageContent = $_ID('page-content');
const response = await postData('/api/v1/category/sub-get', {
UUID: pageURL.searchParams.get('uuid')
})
const response = await getData('/api/v1/client/users/sub-categories/' + pageURL.searchParams.get('id'))
removeByClassName('page-content-loader')
@@ -330,29 +310,33 @@ async function fetchSubCategory() {
async function fetchBannerContent() {
const pageURL = new URL(location);
if (! pageURL.searchParams.has('uuid')) {
if (! pageURL.searchParams.has('id')) {
return;
}
const pageContent = $_ID('page-content');
const bannerId = Number(pageURL.searchParams.get('id'))
const response = await postData('/api/v1/main_slider/get', {
UUID: pageURL.searchParams.get('uuid')
})
const response = await getData('/api/v1/client/users/banners')
const banner = (response.data.banners || []).find(item => item.id === bannerId)
removeByClassName('page-content-loader')
if (! banner) {
return;
}
pageContent.innerHTML = `
<h1 id="page-title" class="uppercase mt-5 mb-5 text-center text-lg green-color text-bold">
${response.data.title[window.locale]}
${banner.title[window.locale]}
</h1>
<div>
<img src="${baseUrl() + response.data.path}" class="w-full">
<img src="${baseUrl() + banner.imagePath}" class="w-full">
</div>
<div>
${response.data.content[window.locale]}
${localizedContent(banner)}
</div>
`;
}
@@ -360,15 +344,13 @@ async function fetchBannerContent() {
async function fetchMiniCategory() {
const pageURL = new URL(location);
if (! pageURL.searchParams.has('uuid')) {
if (! pageURL.searchParams.has('id')) {
return;
}
const pageContent = $_ID('page-content');
const response = await postData('/api/v1/mini_category/get', {
UUID: pageURL.searchParams.get('uuid')
})
const response = await getData('/api/v1/client/users/static/' + pageURL.searchParams.get('id'))
removeByClassName('page-content-loader')
@@ -378,7 +360,7 @@ async function fetchMiniCategory() {
</h1>
<div>
${response.data.content[window.locale]}
${localizedContent(response.data)}
</div>
`;
}
@@ -386,15 +368,13 @@ async function fetchMiniCategory() {
async function fetchNewsContent() {
const pageURL = new URL(location);
if (! pageURL.searchParams.has('uuid')) {
if (! pageURL.searchParams.has('id')) {
return;
}
const pageContent = $_ID('page-content');
const response = await postData('/api/v1/news/get', {
UUID: pageURL.searchParams.get('uuid')
})
const response = await getData('/api/v1/client/users/news/' + pageURL.searchParams.get('id'))
removeByClassName('page-content-loader')
@@ -404,12 +384,12 @@ async function fetchNewsContent() {
</h1>
<div class="mb-5">
<img class="w-full max-h-[600px] object-contain" src="${baseUrl() + response.data.path}">
<img class="w-full max-h-[600px] object-contain" src="${baseUrl() + response.data.imagePath}">
</div>
<div>
<p class="mb-2">
${ new Date(response.data.date).toLocaleDateString('en-GB').replace(/\//g, '.') + 'ý' }
${ new Date(response.data.dateRelease).toLocaleDateString('en-GB').replace(/\//g, '.') + 'ý' }
</p>
${response.data.content[window.locale]}