diff --git a/bot.js b/bot.js index f518119..2e025e2 100644 --- a/bot.js +++ b/bot.js @@ -350,35 +350,58 @@ bot.action(/{"action": "sueta_*/, async (ctx) => { // Обновление меню "Предприятия" bot.hears('🏗️ Предприятия', async (ctx) => { - const user = await UserModel.findByPk(ctx.from.id); - const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); - - const enterprises = await EnterpriseModel.findAll({ - where: { playerId: user.telegram_id } - }); + try { + const user = await UserModel.findByPk(ctx.from.id); + if (!user) { + console.error('Ошибка: пользователь не найден'); + return await ctx.reply('Ошибка: пользователь не найден.'); + } - let message = `🏗️ Меню предприятий:\n`; - message += `У вас: ${enterprises.length} предприятий.\n`; - message += warehouse - ? `🗄️ Единый склад: Доступен (Ёмкость: ${warehouse.capacity} ед.)\n` - : `🗄️ Единый склад: Не построен.\n`; + console.log('ID пользователя:', user.telegram_id); - const buttons = []; + const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); - // Добавляем кнопки для предприятий - buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]); - buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]); + if (!warehouse) { + console.log('Склад не найден для пользователя:', user.telegram_id); + } else { + console.log('Найден склад:', warehouse); + } - // Кнопка для управления или постройки склада - if (warehouse) { - buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]); - } else { - buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]); + const enterprises = await EnterpriseModel.findAll({ + where: { playerId: user.telegram_id } + }); + + if (!enterprises.length) { + console.log('Предприятия не найдены для пользователя:', user.telegram_id); + } else { + console.log('Количество предприятий:', enterprises.length); + } + + let message = `🏗️ Меню предприятий:\n`; + message += `У вас: ${enterprises.length} предприятий.\n`; + message += warehouse + ? `🗄️ Единый склад: Доступен (Ёмкость: ${warehouse.capacity} ед.)\n` + : `🗄️ Единый склад: Не построен.\n`; + + const buttons = []; + buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]); + buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]); + + if (warehouse) { + buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]); + } else { + buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]); + } + + buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }]); + + return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize()); + } catch (error) { + console.error('Ошибка при выполнении команды "🏗️ Предприятия":', error); + return await ctx.reply('Произошла ошибка при выполнении команды. Попробуйте позже.'); } - buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }]) - // Возвращаем меню с кнопками - return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize()); }); + bot.action('enterprise_menu', async (ctx) => { const user = await UserModel.findByPk(ctx.from.id); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); @@ -432,7 +455,9 @@ bot.action('my_enterprises', async (ctx) => { if (enterprises.length === 0) { return await ctx.reply('У вас нет предприятий.'); } - let metallPrice = 0 + let metallPrice = await ResourcePriceModel.findOne({ + where: { resource: "metall" } + }); let message = `🏭 Мои предприятия:\n\n`; const buttons = []; @@ -443,7 +468,6 @@ bot.action('my_enterprises', async (ctx) => { }); let price = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня message += `🔹 [ID: ${id}] ${getEnterpriseEmoji(resourceType)} ${name} st. ${level}\n └── ${currentResources}/${warehouseCapacity} [${efficiency} ед/ч]\n └──📈 ${utils.spaces(price)} руб.\n\n`; - if (resourcePrice.resource == "metall") metallPrice = resourcePrice.price const truck = await TruckModel.findOne({ where: { enterpriseId: id } }); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); @@ -465,7 +489,7 @@ bot.action('my_enterprises', async (ctx) => { buttons.push(enterpriseButtons); } - message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад` + message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice.price*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад` buttons.push([{ text: '⬅️ Назад', callback_data: 'enterprise_menu' }]); return await ctx.editMessageText(message, Markup.inlineKeyboard(buttons).resize()); @@ -530,7 +554,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => { let price = resourcePrice.price * 2 * 10 * 24 * 7 // Проверка, есть ли достаточно денег у пользователя - if (user.balance < price) { + if (user.money < price) { return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, {show_alert: true}) } @@ -577,28 +601,60 @@ function getReadableResourceType(type) { } bot.action('buy_warehouse', async (ctx) => { - let user = await UserModel.findByPk(ctx.from.id) - if (user.status != 'admin') { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Мы работаем над этим.`, {show_alert: true}) - } - if (user.money < 500000) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id,`У вас недостаточно средств для покупки склада.`, {show_alert: true}) - } + try { + // Получаем пользователя + let user = await UserModel.findByPk(ctx.from.id); + if (!user) { + return await ctx.reply('Произошла ошибка. Пользователь не найден.'); + } - await WarehouseModel.create({ - playerId: user.telegram_id, - capacity: 1000, // Начальная ёмкость - wood: 0, - coal: 0, - oil: 0, - metall: 0, - gold: 0, - diamond: 0 - }) + // Получаем цены на металл и дерево + const woodPrice = await ResourcePriceModel.findOne({ where: { resource: 'wood' } }); + const metallPrice = await ResourcePriceModel.findOne({ where: { resource: 'metall' } }); - await user.update({ money: user.money - 500000 }) - return await ctx.reply(`Вы успешно купили единый склад!`) -}) + if (!woodPrice || !metallPrice) { + return await ctx.reply('Не удалось получить цены на ресурсы. Попробуйте позже.'); + } + + // Формируем стоимость склада + const warehouseBaseCost = 10; // Коэффициент для расчёта + const warehouseCost = Math.round( + (woodPrice.price + metallPrice.price) * warehouseBaseCost * 10 * 24 * 7 + ); + + // Проверяем, хватает ли денег у пользователя + if (user.money < warehouseCost) { + return await ctx.telegram.answerCbQuery( + ctx.callbackQuery.id, + `У вас недостаточно средств для покупки склада. Необходимо: ${utils.spaces(warehouseCost)} руб.`, + { show_alert: true } + ); + } + + // Создаём склад + await WarehouseModel.create({ + playerId: user.telegram_id, + capacity: 1000, // Начальная ёмкость + wood: 0, + coal: 0, + oil: 0, + metall: 0, + gold: 0, + diamond: 0, + }); + + // Списываем деньги + await user.update({ money: user.money - warehouseCost }); + + // Уведомление об успешной покупке + return await ctx.reply( + `Вы успешно купили единый склад за ${warehouseCost} руб!` + ); + } catch (error) { + console.error('Ошибка при покупке склада:', error); + return await ctx.reply('Произошла ошибка при покупке склада. Попробуйте позже.'); + } +}); // Управление складом bot.action('manage_warehouse', async (ctx) => { @@ -924,7 +980,7 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => { await resourcePrice.save(); updateResourcePricesMessage(); - await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${resourceType} за ${totalPrice} руб.`); + await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${getEnterpriseEmoji(resourceType)} за ${totalPrice} руб.`); }); // Продажа ресурсов со склада @@ -1170,8 +1226,8 @@ const getWarehouseUsedCapacity = (warehouse) => { return resources.reduce((sum, resource) => sum + (warehouse[resource] || 0), 0); }; -const CHANNEL_ID = '@campfiregg'; // Замените на username вашего канала -let resourceMessageId = 4; // Хранение ID сообщения +const CHANNEL_ID = '@CampFireGameBotNews'; // Замените на username вашего канала +let resourceMessageId = 18; // Хранение ID сообщения const previousPrices = {}; // Объект для хранения предыдущих цен diff --git a/models/enterprise.model.js b/models/enterprise.model.js index 3f60421..d3f5f0f 100644 --- a/models/enterprise.model.js +++ b/models/enterprise.model.js @@ -27,11 +27,8 @@ const Enterprise = sequelize.define('enterprise', { defaultValue: 0 // Начальное количество ресурсов }, playerId: { - type: Sequelize.INTEGER, - references: { - model: 'users', - key: 'telegram_id' - } + type: Sequelize.BIGINT, + allowNull: false } }); diff --git a/models/warehouse.model.js b/models/warehouse.model.js index 86f4c5a..f82bcf7 100644 --- a/models/warehouse.model.js +++ b/models/warehouse.model.js @@ -2,7 +2,7 @@ const sequelize = require('../db'); const {DataTypes} = require('sequelize'); const Warehouse = sequelize.define('warehouse', { - playerId: DataTypes.INTEGER, + playerId: DataTypes.BIGINT, capacity: DataTypes.INTEGER, // Общая ёмкость склада wood: DataTypes.INTEGER, coal: DataTypes.INTEGER,