Compare commits

...

14 Commits

Author SHA1 Message Date
aaeii
6e37fe93f7 изменение админ панели
Some checks failed
platform/multy-stub/pipeline/head There was a failure building this commit
2025-02-08 11:44:00 +03:00
aaeii
f1a93bffb5 fix path 2025-02-08 10:33:24 +03:00
aaeii
f254d57db4 upd json 2025-02-08 09:57:34 +03:00
aaeii
edf9b2c82b add new game, add link 2025-02-05 22:24:05 +03:00
aaeii
801f9ac1e3 new games-in-cart 2025-01-31 20:18:27 +03:00
aaeii
cbbb376fd6 update json gamehub: fix format 2025-01-25 23:24:34 +03:00
aaeii
faaec7c718 update json gamehub: fix price 2025-01-25 23:16:03 +03:00
8814c2a64b Merge pull request 'kazan-explore multy stub changes' (#67) from kazan-explore into master
Reviewed-on: #67
2025-01-24 23:02:53 +03:00
298a82e0ae kazan-explore multy stub changes 2025-01-24 23:02:25 +03:00
a86eb0d4ef Merge pull request 'kazan-explore multy stub changes' (#66) from kazan-explore into master
Reviewed-on: #66
2025-01-24 22:42:50 +03:00
335179ad26 kazan-explore multy stub changes 2025-01-24 22:39:25 +03:00
a1d331b5b4 Merge pull request 'esc stubs fix2' (#65) from esc-stubs into master
Reviewed-on: #65
2025-01-24 16:54:00 +03:00
b36ee36e3a Merge pull request 'esc stubs fix?' (#64) from esc-stubs into master
Reviewed-on: #64
2025-01-24 16:44:45 +03:00
6e0934e585 Merge pull request 'esc stubs' (#63) from esc-stubs into master
Reviewed-on: #63
2025-01-24 16:31:13 +03:00
9 changed files with 573 additions and 458 deletions

View File

@@ -8,22 +8,44 @@ router.get("/update-like", (request, response) => {
response.send(require("./json/gamepage/success.json"));
});
router.get("/categories", (request, response) => {
response.send(require("./json/categories/success.json"));
router.get("/add-to-cart", (request, response) => {
response.send(require("./json/home-page-data/games-in-cart.json"));
});
router.get("/categories", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
router.get("/favourites", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
// router.get("/shopping-cart", (request, response) => {
// response.send(require("./json/shopping-cart/success.json"));
// });
router.get("/shopping-cart", (request, response) => {
response.send(require("./json/shopping-cart/success.json"));
response.send(require("./json/home-page-data/games-in-cart.json"));
});
router.get("/home", (request, response) => {
response.send(require("./json/home-page-data/success.json"));
// Добавляем поддержку разных ответов для /home
router.get("/home", (req, res) => {
if (stubs.home === "success") {
res.send(require("./json/home-page-data/success.json"));
} else if (stubs.home === "empty") {
res.send({ data: [] }); // Отправляем пустой массив
} else {
res.status(500).json({ success: false, message: "Server error" });
}
});
router.get("/all-games", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
const stubs = {
home: "success",
};
// // Маршрут для обновления лайков
// router.post("/update-like", (request, response) => {
@@ -38,7 +60,6 @@ router.get("/all-games", (request, response) => {
// });
// });
const fs = require("fs").promises;
const path = require("path");
@@ -49,7 +70,7 @@ const commentsFilePath = path.join(__dirname, "./json/gamepage/success.json");
async function readComments() {
const data = await fs.readFile(commentsFilePath, "utf-8");
const parsedData = JSON.parse(data);
console.log("Прочитанные данные:", parsedData); // Логируем полученные данные
console.log("Прочитанные данные:", parsedData); // Логируем полученные данные
return parsedData;
}
// Write to JSON file
@@ -88,5 +109,149 @@ router.post("/update-like", async (req, res) => {
}
});
// Путь к JSON-файлу с корзиной
const cartFilePath = path.join(
__dirname,
"./json/home-page-data/games-in-cart.json"
);
// Функция для чтения JSON-файла
async function readCart() {
const data = await fs.readFile(cartFilePath, "utf-8");
return JSON.parse(data);
}
// Функция для записи в JSON-файл
async function writeCart(data) {
await fs.writeFile(cartFilePath, JSON.stringify(data, null, 2), "utf-8");
}
// Маршрут для добавления/удаления товара в корзине
router.post("/add-to-cart", async (req, res) => {
const { id, action } = req.body;
// Проверка наличия id и action
if (id === undefined || action === undefined) {
return res
.status(400)
.json({ success: false, message: "Invalid id or action" });
}
try {
const cartData = await readCart();
let ids = cartData.data.ids;
if (action === "add") {
// Если action "add", добавляем товар, если его нет в корзине
if (!ids?.includes(id)) {
ids.push(id);
}
} else if (action === "remove") {
// Если action "remove", удаляем товар, если он есть в корзине
if (ids?.includes(id)) {
ids = ids.filter((item) => item !== id);
}
} else {
// Если action невалиден
return res
.status(400)
.json({ success: false, message: "Invalid action" });
}
// Записываем обновленные данные обратно в файл
cartData.data.ids = ids;
await writeCart(cartData);
res.status(200).json({
success: true,
message: "Cart updated successfully",
data: cartData.data, // Возвращаем обновленные данные
});
} catch (error) {
console.error("Error updating cart:", error);
res.status(500).json({ success: false, message: "Server error" });
}
});
module.exports = router;
const createElement = (key, value, buttonTitle, basePath) => `
<label>
<input name="${key}" type="radio" ${
stubs[key] === value ? "checked" : ""
} onclick="fetch('${basePath}/admin/set/${key}/${value}')"/>
${buttonTitle || value}
</label>
`;
router.get("/admin/home", (request, response) => {
const basePath = request.baseUrl; // Получаем базовый путь маршрутизатора
response.send(`
<div>
<fieldset>
<legend>Настройка данных для /home</legend>
${createElement("home", "success", "Отдать успешный ответ", basePath)}
${createElement("home", "empty", "Отдать пустой массив", basePath)}
${createElement("home", "error", "Отдать ошибку", basePath)}
</fieldset>
</div>
`);
});
router.get("/admin/game-page", (request, response) => {
response.send(`
<div>
<fieldset>
<legend>Настройка данных для /game-page</legend>
${createElement(
"game-page",
"success",
"Отдать успешный ответ"
)}
${createElement("game-page", "empty", "Отдать пустой массив")}
${createElement("game-page", "error", "Отдать ошибку")}
</fieldset>
</div>
`);
});
router.get("/admin/categories", (request, response) => {
response.send(`
<div>
<fieldset>
<legend>Настройка данных для /categories</legend>
${createElement(
"categories",
"success",
"Отдать успешный ответ"
)}
${createElement("categories", "empty", "Отдать пустой массив")}
${createElement("categories", "error", "Отдать ошибку")}
</fieldset>
</div>
`);
});
router.get("/admin/favourites", (request, response) => {
response.send(`
<div>
<fieldset>
<legend>Настройка данных для /favourites</legend>
${createElement(
"favourites",
"success",
"Отдать успешный ответ"
)}
${createElement("favourites", "empty", "Отдать пустой массив")}
${createElement("favourites", "error", "Отдать ошибку")}
</fieldset>
</div>
`);
});
router.get("/admin/set/:key/:value", (request, response) => {
const { key, value } = request.params;
stubs[key] = value;
response.send("Настройки обновлены!");
});

View File

@@ -1,186 +0,0 @@
{
"success": true,
"data": {
"games1": [
{
"id": 1,
"title": "How to Survive",
"price": 259,
"old_price": 500,
"image": "sales_game1",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 2,
"title": "Red Solstice 2 Survivors",
"price": 561,
"image": "sales_game2",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 3,
"title": "Sons Of The Forests",
"price": 820,
"old_price": 1100,
"image": "new_game2",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
}
],
"games2": [
{
"id": 7,
"title": "Alpha League",
"price": 299,
"image": "new_game1",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 8,
"title": "Sons Of The Forests",
"price": 820,
"old_price": 1100,
"image": "new_game2",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 9,
"title": "Pacific Drives",
"price": 1799,
"image": "new_game3",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
}
],
"games3": [
{
"id": 10,
"title": "Elden Ring",
"price": 3295,
"old_price": 3599,
"image": "leaders_game2",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 11,
"title": "Counter-Strike 2",
"price": 479,
"image": "leaders_game1",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 12,
"title": "PUBG: BATTLEGROUNDS",
"price": 199,
"image": "leaders_game3",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows",
"fav1": "star1",
"fav2": "star2"
}
]
}
}

View File

@@ -5,28 +5,28 @@
{
"username": ользователь1",
"text": "Текст комментария 1",
"likes": 9,
"likes": 13,
"rating": 8,
"date": "2025-03-01T10:00:00Z"
},
{
"username": ользователь2",
"text": "Текст комментария 2",
"likes": 7,
"likes": 10,
"rating": 7,
"date": "2025-01-01T10:00:00Z"
},
{
"username": ользователь3",
"text": "Текст комментария 3",
"likes": 5,
"likes": 4,
"rating": 3,
"date": "2025-02-01T10:00:00Z"
},
{
"username": ользователь4",
"text": "Текст комментария 4",
"likes": 15,
"likes": 18,
"rating": 2,
"date": "2025-12-01T10:00:00Z"
}

View File

@@ -3,144 +3,183 @@
"data": [
{
"id": 1,
"name": "The Witcher 3: Wild Hunt",
"image": "game1",
"text": "$10",
"imgPath": "img_top_1",
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
"title": "Elden Ring",
"image": "game17",
"price": 3295,
"old_price": 3599,
"imgPath": "img_top_17",
"description": "Крупномасштабная RPG, действие которой происходит в обширном открытом мире c богатой мифологией и множеством опасных врагов.",
"category": "RPG"
},
{
"id": 2,
"name": "Red Dead Redemption 2",
"title": "The Witcher 3: Wild Hunt",
"image": "game1",
"price": 990,
"old_price": 1200,
"imgPath": "img_top_1",
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
"category": "RPG"
},
{
"id": 17,
"title": "Red Dead Redemption 2",
"image": "game2",
"text": "$10",
"price": 980,
"old_price": 3800,
"imgPath": "img_top_2",
"description": "Приключенческая игра с открытым миром на Диком Западе, рассказывающая историю Артура Моргана.",
"category": "Adventures"
},
{
"id": 3,
"name": "Forza Horizon 5",
"title": "Forza Horizon 5",
"image": "game3",
"text": "$10",
"price": 1900,
"imgPath": "img_top_3",
"description": "Гоночная игра с огромным открытым миром, действие которой происходит в Мексике.",
"category": "Race"
},
{
"id": 4,
"name": "Atomic Heart",
"title": "Atomic Heart",
"image": "game4",
"text": "$10",
"price": 1200,
"old_price": 2500,
"imgPath": "img_top_4",
"description": "Экшен-шутер с элементами RPG, разворачивающийся в альтернативной Советской России.",
"category": "Shooters"
},
{
"id": 5,
"name": "Counter-Strike 2",
"title": "Counter-Strike 2",
"image": "game5",
"text": "$10",
"price": 479,
"imgPath": "img_top_5",
"description": "Популярный онлайн-шутер с соревновательным геймплеем и тактическими элементами.",
"category": "Shooters"
},
{
"id": 6,
"name": "Grand Theft Auto V",
"title": "Grand Theft Auto V",
"image": "game6",
"text": "$10",
"price": 700,
"imgPath": "img_top_6",
"description": "Игра с открытым миром, где можно погрузиться в криминальный мир Лос-Сантоса.",
"category": "Adventures"
},
{
"id": 7,
"name": "Assassins Creed IV: Black Flag",
"title": "Assassins Creed IV: Black Flag",
"image": "game7",
"text": "$10",
"price": 1100,
"imgPath": "img_top_7",
"description": "Приключенческая игра о пиратах и морских сражениях в эпоху золотого века пиратства.",
"category": "Adventures"
},
{
"id": 8,
"name": "Spider-Man",
"title": "Spider-Man",
"image": "game8",
"text": "$10",
"price": 3800,
"imgPath": "img_top_8",
"description": "Игра о супергерое Человеке-пауке с захватывающими битвами и паркуром по Нью-Йорку.",
"category": "Action"
},
{
"id": 9,
"name": "Assassins Creed Mirage",
"title": "Assassins Creed Mirage",
"image": "game9",
"text": "$10",
"price": 1600,
"imgPath": "img_top_9",
"description": "Приключенческая игра с упором на скрытность, вдохновленная классическими частями серии.",
"category": "Action"
},
{
"id": 10,
"name": "Assassins Creed Valhalla",
"title": "Assassins Creed Valhalla",
"image": "game10",
"text": "$10",
"price": 800,
"old_price": 2200,
"imgPath": "img_top_10",
"description": "RPG с открытым миром о викингах, включающая битвы, исследования и строительство поселений.",
"category": "RPG"
},
{
"id": 11,
"name": "ARK: Survival Evolved",
"title": "ARK: Survival Evolved",
"image": "game11",
"text": "$10",
"price": 790,
"imgPath": "img_top_11",
"description": "Выживание в открытом мире с динозаврами, строительством и многопользовательскими элементами.",
"category": "Simulators"
},
{
"id": 12,
"name": "FIFA 23",
"title": "FIFA 23",
"image": "game12",
"text": "$10",
"price": 3900,
"imgPath": "img_top_12",
"description": "Популярный футбольный симулятор с улучшенной графикой и реалистичным геймплеем.",
"category": "Sports"
},
{
"id": 13,
"name": "Dirt 5",
"title": "Dirt 5",
"image": "game13",
"text": "$10",
"price": 2300,
"imgPath": "img_top_13",
"description": "Аркадная гоночная игра с фокусом на ралли и внедорожных соревнованиях.",
"category": "Race"
},
{
"id": 14,
"name": "Cyberpunk 2077",
"title": "Cyberpunk 2077",
"image": "game14",
"text": "$10",
"price": 3400,
"imgPath": "img_top_14",
"description": "RPG в киберпанк-сеттинге с нелинейным сюжетом и детализированным открытым миром.",
"category": "RPG"
},
{
"id": 15,
"name": "Age of Empires IV",
"title": "Age of Empires IV",
"image": "game15",
"text": "$10",
"price": 3200,
"imgPath": "img_top_15",
"description": "Классическая стратегия в реальном времени с историческими кампаниями.",
"category": "Strategies"
},
{
"id": 16,
"name": "Civilization VI",
"title": "Civilization VI",
"image": "game16",
"text": "$10",
"price": 4200,
"imgPath": "img_top_16",
"description": "Глобальная пошаговая стратегия, в которой игроки строят и развивают цивилизации.",
"category": "Strategies"

View File

@@ -0,0 +1,16 @@
{
"success": true,
"data": {
"ids": [
3,
13,
1,
10,
4,
9,
15,
6,
7
]
}
}

View File

@@ -3,43 +3,51 @@
"data": {
"topSail": [
{
"id": 1,
"image": "game1",
"text": "$10",
"price": 1500,
"imgPath": "img_top_1"
},
{
"id": 2,
"image": "game2",
"text": "$10",
"price": 980,
"imgPath": "img_top_2"
},
{
"id": 3,
"image": "game3",
"text": "$10",
"price": 1900,
"imgPath": "img_top_3"
},
{
"id": 4,
"image": "game4",
"text": "$10",
"price": 1200,
"imgPath": "img_top_4"
},
{
"id": 5,
"image": "game5",
"text": "$10",
"price": 479,
"imgPath": "img_top_5"
},
{
"id": 6,
"image": "game6",
"text": "$10",
"price": 700,
"imgPath": "img_top_6"
},
{
"id": 7,
"image": "game7",
"text": "$10",
"price": 1100,
"imgPath": "img_top_7"
},
{
"id": 8,
"image": "game8",
"text": "$10",
"price": 3800,
"imgPath": "img_top_8"
}
],
@@ -97,22 +105,26 @@
{
"image": "news1",
"text": "Разработчики Delta Force: Hawk Ops представили крупномасштабный режим Havoc Warfare",
"imgPath": "img_news_1"
"imgPath": "img_news_1",
"link": "https://gamemag.ru/news/185583/delta-force-hawk-ops-gameplay-showcase-havoc-warfare"
},
{
"image": "news2",
"text": "Первый трейлер Assassins Creed Shadows — с темнокожим самураем в феодальной Японии",
"imgPath": "img_news_2"
"imgPath": "img_news_2",
"link": "https://stopgame.ru/newsdata/62686/pervyy_trailer_assassin_s_creed_shadows_s_temnokozhim_samuraem_v_feodalnoy_yaponii"
},
{
"image": "news3",
"text": "Призрак Цусимы» вышел на ПК — и уже ставит рекорды для Sony",
"imgPath": "img_news_3"
"imgPath": "img_news_3",
"link": "https://stopgame.ru/newsdata/62706/prizrak_cusimy_vyshel_na_pk_i_uzhe_stavit_rekordy_dlya_sony"
},
{
"image": "news4",
"text": "Авторы Skull and Bones расширяют планы на второй сезо",
"imgPath": "img_news_4"
"text": "Авторы Skull and Bones расширяют планы на второй сезон",
"imgPath": "img_news_4",
"link": "https://stopgame.ru/newsdata/62711/avtory_skull_and_bones_rasshiryayut_plany_na_vtoroy_sezon"
}
]
}

View File

@@ -0,0 +1,3 @@
exports.KAZAN_EXPLORE_RESULTS_MODEL_NAME = 'KAZAN_EXPLORE_RESULTS'
exports.TOKEN_KEY = "KAZAN_EXPLORE_TOP_SECRET_TOKEN_KEY"

View File

@@ -1,15 +1,54 @@
const router = require('express').Router();
const { ResultsModel } = require('./model/results')
router.get('/getQuizResults/:userId', async (request, response) => {
const { userId } = request.params;
try {
const results = await ResultsModel.findOne({ userId : userId }).exec();
if (!results) {
return response.status(404).send({ message: 'Quiz results not found' });
}
response.send(results.items);
} catch (error) {
response.status(500).send({ message: 'An error occurred while fetching quiz results' });
}
});
router.post('/addQuizResult', async (request, response) => {
const { userId, quizId, result } = request.body;
if (!userId || !quizId || !result) {
return response.status(400).send({ message: 'Invalid input data' });
}
try {
let userResults = await ResultsModel.findOne({ userId : userId }).exec();
if (!userResults) {
userResults = new ResultsModel({ userId, items: [] });
}
userResults.items.push({ quizId, result });
await userResults.save();
response.status(200).send({ message: 'Quiz result added successfully', data: userResults });
} catch (error) {
response.status(500).send({ message: 'An error occurred while adding quiz result' });
}
});
// First page
router.get('/getInfoAboutKazan', (request, response) => {
const lang = request.query.lang || 'ru'; // Получаем язык из параметров запроса
const lang = request.query.lang || 'ru';
try {
const data = require('./json/first/info-about-kazan/success.json'); // Загружаем весь JSON
const translatedData = data[lang] || data['ru']; // Выбираем перевод по языку или дефолтный
response.send(translatedData); // Отправляем перевод клиенту
const data = require('./json/first/info-about-kazan/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(500).send({ message: 'Internal server error' }); // Ошибка в случае проблем с JSON
response.status(500).send({ message: 'Internal server error' });
}
});
@@ -25,13 +64,13 @@ router.get('/getNews', (request, response) => {
// Sport page
router.get('/getFirstText', (request, response) => {
const lang = request.query.lang || 'ru'; // Получаем язык из параметров
const lang = request.query.lang || 'ru';
try {
const data = require('./json/sport/first-text/success.json'); // Загружаем JSON
const translatedData = data[lang] || data['ru']; // Берём перевод или дефолтный
const data = require('./json/sport/first-text/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' }); // Обработка ошибки
response.status(404).send({ message: 'Language not found' });
}
});

View File

@@ -0,0 +1,27 @@
const { Schema, model } = require('mongoose')
const { KAZAN_EXPLORE_RESULTS_MODEL_NAME } = require('../const')
const schema = new Schema({
userId: { type: String },
items: [
{
quizId: { type: String },
result: { type: Number }
}
]
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
transform: function (doc, ret) {
delete ret._id
}
})
schema.virtual('id').get(function () {
return this._id.toHexString()
})
exports.ResultsModel = model(KAZAN_EXPLORE_RESULTS_MODEL_NAME, schema)