Users location edition added

This commit is contained in:
Artyom Ashirov 2024-11-14 20:16:17 +03:00
parent 52779d20ab
commit 2beaa324fa
2 changed files with 394 additions and 218 deletions

View File

@ -0,0 +1,160 @@
import db from '../config/database.js';
import Validators from '../utils/validators.js';
export default class AdminUserLocationHandler {
constructor(bot) {
this.bot = bot;
}
async handleEditUserLocation(callbackQuery) {
const userId = callbackQuery.data.replace('edit_user_location_', '');
const chatId = callbackQuery.message.chat.id;
const messageId = callbackQuery.message.message_id;
try {
const countries = await db.allAsync('SELECT DISTINCT country FROM locations ORDER BY country');
if (countries.length === 0) {
await this.bot.editMessageText(
'No locations available yet.',
{
chat_id: chatId,
message_id: messageId,
reply_markup: {
inline_keyboard: [[
{ text: '« Back to User', callback_data: `view_user_${userId}` }
]]
}
}
);
return;
}
const keyboard = {
inline_keyboard: [
...countries.map(loc => [{
text: loc.country,
callback_data: `edit_user_country_${loc.country}_${userId}`
}]),
[{ text: '« Back to User', callback_data: `view_user_${userId}` }]
]
};
await this.bot.editMessageText(
'🌍 Select user country:',
{
chat_id: chatId,
message_id: messageId,
reply_markup: keyboard
}
);
} catch (error) {
console.error('Error in handleSetLocation:', error);
await this.bot.sendMessage(chatId, 'Error loading countries. Please try again.');
}
}
async handleEditUserCountry(callbackQuery) {
const chatId = callbackQuery.message.chat.id;
const messageId = callbackQuery.message.message_id;
const [country, userId] = callbackQuery.data.replace('edit_user_country_', '').split("_");
try {
const cities = await db.allAsync(
'SELECT DISTINCT city FROM locations WHERE country = ? ORDER BY city',
[country]
);
const keyboard = {
inline_keyboard: [
...cities.map(loc => [{
text: loc.city,
callback_data: `edit_user_city_${country}_${loc.city}_${userId}`
}]),
[{ text: '« Back to Countries', callback_data: `edit_user_location_${userId}` }]
]
};
await this.bot.editMessageText(
`🏙 Select city in ${country}:`,
{
chat_id: chatId,
message_id: messageId,
reply_markup: keyboard
}
);
} catch (error) {
console.error('Error in handleSetCountry:', error);
await this.bot.sendMessage(chatId, 'Error loading cities. Please try again.');
}
}
async handleEditUserCity(callbackQuery) {
const chatId = callbackQuery.message.chat.id;
const messageId = callbackQuery.message.message_id;
const [country, city, userId] = callbackQuery.data.replace('edit_user_city_', '').split('_');
try {
const districts = await db.allAsync(
'SELECT district FROM locations WHERE country = ? AND city = ? ORDER BY district',
[country, city]
);
const keyboard = {
inline_keyboard: [
...districts.map(loc => [{
text: loc.district,
callback_data: `edit_user_district_${country}_${city}_${loc.district}_${userId}`
}]),
[{ text: '« Back to Cities', callback_data: `edit_user_country_${country}_${userId}` }]
]
};
await this.bot.editMessageText(
`📍 Select district in ${city}:`,
{
chat_id: chatId,
message_id: messageId,
reply_markup: keyboard
}
);
} catch (error) {
console.error('Error in handleSetCity:', error);
await this.bot.sendMessage(chatId, 'Error loading districts. Please try again.');
}
}
async handleEditUserDistrict(callbackQuery) {
const chatId = callbackQuery.message.chat.id;
const messageId = callbackQuery.message.message_id;
const [country, city, district, userId] = callbackQuery.data.replace('edit_user_district_', '').split('_');
try {
await db.runAsync('BEGIN TRANSACTION');
await db.runAsync(
'UPDATE users SET country = ?, city = ?, district = ? WHERE telegram_id = ?',
[country, city, district, userId.toString()]
);
await db.runAsync('COMMIT');
await this.bot.editMessageText(
`✅ Location updated successfully!\n\nCountry: ${country}\nCity: ${city}\nDistrict: ${district}`,
{
chat_id: chatId,
message_id: messageId,
reply_markup: {
inline_keyboard: [[
{ text: '« Back to User', callback_data: `view_user_${userId}` }
]]
}
}
);
} catch (error) {
await db.runAsync('ROLLBACK');
console.error('Error in handleSetDistrict:', error);
await this.bot.sendMessage(chatId, 'Error updating location. Please try again.');
}
}
}

View File

@ -10,22 +10,23 @@ import AdminLocationHandler from './handlers/adminLocationHandler.js';
import AdminProductHandler from './handlers/adminProductHandler.js';
import ErrorHandler from './utils/errorHandler.js';
import User from './models/User.js';
import AdminUserLocationHandler from "./handlers/adminUserLocationHandler.js";
// Debug logging function
const logDebug = (action, functionName) => {
console.log(`[DEBUG] Button Press: ${action}`);
console.log(`[DEBUG] Calling Function: ${functionName}`);
console.log(`[DEBUG] Button Press: ${action}`);
console.log(`[DEBUG] Calling Function: ${functionName}`);
};
const initBot = () => {
try {
const bot = new TelegramBot(config.BOT_TOKEN, { polling: true });
console.log('Bot initialized successfully');
return bot;
} catch (error) {
console.error('Failed to initialize bot:', error);
process.exit(1);
}
try {
const bot = new TelegramBot(config.BOT_TOKEN, {polling: true});
console.log('Bot initialized successfully');
return bot;
} catch (error) {
console.error('Failed to initialize bot:', error);
process.exit(1);
}
};
const bot = initBot();
@ -36,243 +37,258 @@ const userLocationHandler = new UserLocationHandler(bot);
const adminHandler = new AdminHandler(bot);
const adminUserHandler = new AdminUserHandler(bot);
const adminLocationHandler = new AdminLocationHandler(bot);
const adminUserLocationHandler = new AdminUserLocationHandler(bot);
const adminProductHandler = new AdminProductHandler(bot);
// Start command - Create user profile
bot.onText(/\/start/, async (msg) => {
logDebug('/start', 'handleStart');
try {
await userHandler.handleStart(msg);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'start command');
}
logDebug('/start', 'handleStart');
try {
await userHandler.handleStart(msg);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'start command');
}
});
// Admin command
bot.onText(/\/admin/, async (msg) => {
logDebug('/admin', 'handleAdminCommand');
try {
await adminHandler.handleAdminCommand(msg);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'admin command');
}
logDebug('/admin', 'handleAdminCommand');
try {
await adminHandler.handleAdminCommand(msg);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'admin command');
}
});
// Handle user menu buttons
bot.on('message', async (msg) => {
if (!msg.text) return;
if (!msg.text) return;
try {
// Check for admin location input
if (await adminLocationHandler.handleLocationInput(msg)) {
return;
}
// Check for admin category input
if (await adminProductHandler.handleCategoryInput(msg)) {
return;
}
// Check for admin subcategory input
if (await adminProductHandler.handleSubcategoryInput(msg)) {
return;
}
// Check for product import
if (await adminProductHandler.handleProductImport(msg)) {
return;
}
logDebug(msg.text, 'handleMessage');
switch (msg.text) {
case '📦 Products':
await userProductHandler.showProducts(msg);
break;
case '👤 Profile':
await userHandler.showProfile(msg);
break;
case '💰 Wallets':
await userWalletsHandler.showBalance(msg);
break;
case '🛍 Purchases':
await userProductHandler.showPurchases(msg);
break;
case '📦 Manage Products':
if (adminHandler.isAdmin(msg.from.id)) {
await adminProductHandler.handleProductManagement(msg);
try {
// Check for admin location input
if (await adminLocationHandler.handleLocationInput(msg)) {
return;
}
break;
case '👥 Manage Users':
if (adminHandler.isAdmin(msg.from.id)) {
await adminUserHandler.handleUserList(msg);
// Check for admin category input
if (await adminProductHandler.handleCategoryInput(msg)) {
return;
}
break;
case '📍 Manage Locations':
if (adminHandler.isAdmin(msg.from.id)) {
await adminLocationHandler.handleViewLocations(msg);
// Check for admin subcategory input
if (await adminProductHandler.handleSubcategoryInput(msg)) {
return;
}
break;
// Check for product import
if (await adminProductHandler.handleProductImport(msg)) {
return;
}
logDebug(msg.text, 'handleMessage');
switch (msg.text) {
case '📦 Products':
await userProductHandler.showProducts(msg);
break;
case '👤 Profile':
await userHandler.showProfile(msg);
break;
case '💰 Wallets':
await userWalletsHandler.showBalance(msg);
break;
case '🛍 Purchases':
await userProductHandler.showPurchases(msg);
break;
case '📦 Manage Products':
if (adminHandler.isAdmin(msg.from.id)) {
await adminProductHandler.handleProductManagement(msg);
}
break;
case '👥 Manage Users':
if (adminHandler.isAdmin(msg.from.id)) {
await adminUserHandler.handleUserList(msg);
}
break;
case '📍 Manage Locations':
if (adminHandler.isAdmin(msg.from.id)) {
await adminLocationHandler.handleViewLocations(msg);
}
break;
}
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'message handler');
}
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'message handler');
}
});
// Handle callback queries
bot.on('callback_query', async (callbackQuery) => {
const action = callbackQuery.data;
const msg = callbackQuery.message;
const action = callbackQuery.data;
const msg = callbackQuery.message;
try {
// Profile and location management
if (action === 'set_location') {
logDebug(action, 'handleSetLocation');
await userLocationHandler.handleSetLocation(callbackQuery);
} else if (action.startsWith('set_country_')) {
logDebug(action, 'handleSetCountry');
await userLocationHandler.handleSetCountry(callbackQuery);
} else if (action.startsWith('set_city_')) {
logDebug(action, 'handleSetCity');
await userLocationHandler.handleSetCity(callbackQuery);
} else if (action.startsWith('set_district_')) {
logDebug(action, 'handleSetDistrict');
await userLocationHandler.handleSetDistrict(callbackQuery);
} else if (action === 'back_to_profile') {
logDebug(action, 'handleBackToProfile');
await userHandler.handleBackToProfile(callbackQuery);
} else if (action === 'back_to_balance') {
logDebug(action, 'handleBackToBalance');
await userWalletsHandler.handleBackToBalance(callbackQuery);
try {
// Profile and location management
if (action === 'set_location') {
logDebug(action, 'handleSetLocation');
await userLocationHandler.handleSetLocation(callbackQuery);
} else if (action.startsWith('set_country_')) {
logDebug(action, 'handleSetCountry');
await userLocationHandler.handleSetCountry(callbackQuery);
} else if (action.startsWith('set_city_')) {
logDebug(action, 'handleSetCity');
await userLocationHandler.handleSetCity(callbackQuery);
} else if (action.startsWith('set_district_')) {
logDebug(action, 'handleSetDistrict');
await userLocationHandler.handleSetDistrict(callbackQuery);
} else if (action === 'back_to_profile') {
logDebug(action, 'handleBackToProfile');
await userHandler.handleBackToProfile(callbackQuery);
} else if (action === 'back_to_balance') {
logDebug(action, 'handleBackToBalance');
await userWalletsHandler.handleBackToBalance(callbackQuery);
}
// Wallet management
else if (action === 'add_wallet') {
logDebug(action, 'handleAddWallet');
await userWalletsHandler.handleAddWallet(callbackQuery);
} else if (action === 'top_up_wallet') {
logDebug(action, 'handleTopUpWallet');
await userWalletsHandler.handleTopUpWallet(callbackQuery);
} else if (action === 'wallet_history') {
logDebug(action, 'handleWalletHistory');
await userWalletsHandler.handleWalletHistory(callbackQuery);
} else if (action === 'view_archived_wallets') {
logDebug(action, 'handleViewArchivedWallets');
await userWalletsHandler.handleViewArchivedWallets(callbackQuery);
} else if (action === 'refresh_balance') {
logDebug(action, 'handleRefreshBalance');
await userWalletsHandler.handleRefreshBalance(callbackQuery);
}
// Wallet generation
else if (action.startsWith('generate_wallet_')) {
logDebug(action, 'handleGenerateWallet');
await userWalletsHandler.handleGenerateWallet(callbackQuery);
}
// Shop navigation
else if (action === 'shop_start') {
logDebug(action, 'showProducts');
await userProductHandler.showProducts(msg);
} else if (action.startsWith('shop_country_')) {
logDebug(action, 'handleCountrySelection');
await userProductHandler.handleCountrySelection(callbackQuery);
} else if (action.startsWith('shop_city_')) {
logDebug(action, 'handleCitySelection');
await userProductHandler.handleCitySelection(callbackQuery);
} else if (action.startsWith('shop_district_')) {
logDebug(action, 'handleDistrictSelection');
await userProductHandler.handleDistrictSelection(callbackQuery);
} else if (action.startsWith('shop_category_')) {
logDebug(action, 'handleCategorySelection');
await userProductHandler.handleCategorySelection(callbackQuery);
} else if (action.startsWith('shop_subcategory_')) {
logDebug(action, 'handleSubcategorySelection');
await userProductHandler.handleSubcategorySelection(callbackQuery);
} else if (action.startsWith('shop_product_')) {
logDebug(action, 'handleProductSelection');
await userProductHandler.handleProductSelection(callbackQuery);
} else if (action.startsWith('increase_quantity_')) {
logDebug(action, 'handleIncreaseQuantity');
await userProductHandler.handleIncreaseQuantity(callbackQuery);
} else if (action.startsWith('decrease_quantity_')) {
logDebug(action, 'handleDecreaseQuantity');
await userProductHandler.handleDecreaseQuantity(callbackQuery);
} else if (action.startsWith('buy_product_')) {
logDebug(action, 'handleBuyProduct');
await userProductHandler.handleBuyProduct(callbackQuery);
}
// Admin location management
else if (action === 'add_location') {
logDebug(action, 'handleAddLocation');
await adminLocationHandler.handleAddLocation(callbackQuery);
} else if (action === 'view_locations') {
logDebug(action, 'handleViewLocations');
await adminLocationHandler.handleViewLocations(callbackQuery);
} else if (action === 'delete_location') {
logDebug(action, 'handleDeleteLocation');
await adminLocationHandler.handleDeleteLocation(callbackQuery);
} else if (action.startsWith('confirm_delete_')) {
logDebug(action, 'handleConfirmDelete');
await adminLocationHandler.handleConfirmDelete(callbackQuery);
}
// Admin product management
else if (action === 'manage_products') {
logDebug(action, 'handleProductManagement');
await adminProductHandler.handleProductManagement(callbackQuery);
} else if (action.startsWith('prod_country_')) {
logDebug(action, 'handleCountrySelection');
await adminProductHandler.handleCountrySelection(callbackQuery);
} else if (action.startsWith('prod_city_')) {
logDebug(action, 'handleCitySelection');
await adminProductHandler.handleCitySelection(callbackQuery);
} else if (action.startsWith('prod_district_')) {
logDebug(action, 'handleDistrictSelection');
await adminProductHandler.handleDistrictSelection(callbackQuery);
} else if (action.startsWith('add_category_')) {
logDebug(action, 'handleAddCategory');
await adminProductHandler.handleAddCategory(callbackQuery);
} else if (action.startsWith('edit_category_')) {
logDebug(action, 'handleEditCategory');
await adminProductHandler.handleEditCategory(callbackQuery);
} else if (action.startsWith('prod_category_')) {
logDebug(action, 'handleCategorySelection');
await adminProductHandler.handleCategorySelection(callbackQuery);
} else if (action.startsWith('add_subcategory_')) {
logDebug(action, 'handleAddSubcategory');
await adminProductHandler.handleAddSubcategory(callbackQuery);
} else if (action.startsWith('prod_subcategory_')) {
logDebug(action, 'handleSubcategorySelection');
await adminProductHandler.handleSubcategorySelection(callbackQuery);
} else if (action.startsWith('add_product_')) {
logDebug(action, 'handleAddProduct');
await adminProductHandler.handleAddProduct(callbackQuery);
} else if (action.startsWith('view_product_')) {
logDebug(action, 'handleViewProduct');
await adminProductHandler.handleViewProduct(callbackQuery);
}
// Admin user management
else if (action.startsWith('view_user_')) {
logDebug(action, 'handleViewUser');
await adminUserHandler.handleViewUser(callbackQuery);
} else if (action.startsWith('delete_user_')) {
logDebug(action, 'handleDeleteUser');
await adminUserHandler.handleDeleteUser(callbackQuery);
} else if (action.startsWith('confirm_delete_user_')) {
logDebug(action, 'handleConfirmDelete');
await adminUserHandler.handleConfirmDelete(callbackQuery);
} else if (action.startsWith('edit_user_balance_')) {
logDebug(action, 'handleEditUserBalance');
await adminUserHandler.handleEditUserBalance(callbackQuery);
}
// Admin users location management
else if (action.startsWith('edit_user_location_')) {
logDebug(action, 'handleEditUserLocation');
await adminUserLocationHandler.handleEditUserLocation(callbackQuery);
} else if (action.startsWith('edit_user_country_')) {
logDebug(action, 'handleEditUserCountry');
await adminUserLocationHandler.handleEditUserCountry(callbackQuery);
} else if (action.startsWith('edit_user_city_')) {
logDebug(action, 'handleEditUserCity');
await adminUserLocationHandler.handleEditUserCity(callbackQuery);
} else if (action.startsWith('edit_user_district_')) {
logDebug(action, 'handleEditUserDistrict');
await adminUserLocationHandler.handleEditUserDistrict(callbackQuery)
}
await bot.answerCallbackQuery(callbackQuery.id);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'callback query');
}
// Wallet management
else if (action === 'add_wallet') {
logDebug(action, 'handleAddWallet');
await userWalletsHandler.handleAddWallet(callbackQuery);
} else if (action === 'top_up_wallet') {
logDebug(action, 'handleTopUpWallet');
await userWalletsHandler.handleTopUpWallet(callbackQuery);
} else if (action === 'wallet_history') {
logDebug(action, 'handleWalletHistory');
await userWalletsHandler.handleWalletHistory(callbackQuery);
} else if (action === 'view_archived_wallets') {
logDebug(action, 'handleViewArchivedWallets');
await userWalletsHandler.handleViewArchivedWallets(callbackQuery);
} else if (action === 'refresh_balance') {
logDebug(action, 'handleRefreshBalance');
await userWalletsHandler.handleRefreshBalance(callbackQuery);
}
// Wallet generation
else if (action.startsWith('generate_wallet_')) {
logDebug(action, 'handleGenerateWallet');
await userWalletsHandler.handleGenerateWallet(callbackQuery);
}
// Shop navigation
else if (action === 'shop_start') {
logDebug(action, 'showProducts');
await userProductHandler.showProducts(msg);
} else if (action.startsWith('shop_country_')) {
logDebug(action, 'handleCountrySelection');
await userProductHandler.handleCountrySelection(callbackQuery);
} else if (action.startsWith('shop_city_')) {
logDebug(action, 'handleCitySelection');
await userProductHandler.handleCitySelection(callbackQuery);
} else if (action.startsWith('shop_district_')) {
logDebug(action, 'handleDistrictSelection');
await userProductHandler.handleDistrictSelection(callbackQuery);
} else if (action.startsWith('shop_category_')) {
logDebug(action, 'handleCategorySelection');
await userProductHandler.handleCategorySelection(callbackQuery);
} else if (action.startsWith('shop_subcategory_')) {
logDebug(action, 'handleSubcategorySelection');
await userProductHandler.handleSubcategorySelection(callbackQuery);
} else if (action.startsWith('shop_product_')) {
logDebug(action, 'handleProductSelection');
await userProductHandler.handleProductSelection(callbackQuery);
} else if (action.startsWith('increase_quantity_')) {
logDebug(action, 'handleIncreaseQuantity');
await userProductHandler.handleIncreaseQuantity(callbackQuery);
} else if (action.startsWith('decrease_quantity_')) {
logDebug(action, 'handleDecreaseQuantity');
await userProductHandler.handleDecreaseQuantity(callbackQuery);
} else if (action.startsWith('buy_product_')) {
logDebug(action, 'handleBuyProduct');
await userProductHandler.handleBuyProduct(callbackQuery);
}
// Admin location management
else if (action === 'add_location') {
logDebug(action, 'handleAddLocation');
await adminLocationHandler.handleAddLocation(callbackQuery);
} else if (action === 'view_locations') {
logDebug(action, 'handleViewLocations');
await adminLocationHandler.handleViewLocations(callbackQuery);
} else if (action === 'delete_location') {
logDebug(action, 'handleDeleteLocation');
await adminLocationHandler.handleDeleteLocation(callbackQuery);
} else if (action.startsWith('confirm_delete_')) {
logDebug(action, 'handleConfirmDelete');
await adminLocationHandler.handleConfirmDelete(callbackQuery);
}
// Admin product management
else if (action === 'manage_products') {
logDebug(action, 'handleProductManagement');
await adminProductHandler.handleProductManagement(callbackQuery);
} else if (action.startsWith('prod_country_')) {
logDebug(action, 'handleCountrySelection');
await adminProductHandler.handleCountrySelection(callbackQuery);
} else if (action.startsWith('prod_city_')) {
logDebug(action, 'handleCitySelection');
await adminProductHandler.handleCitySelection(callbackQuery);
} else if (action.startsWith('prod_district_')) {
logDebug(action, 'handleDistrictSelection');
await adminProductHandler.handleDistrictSelection(callbackQuery);
} else if (action.startsWith('add_category_')) {
logDebug(action, 'handleAddCategory');
await adminProductHandler.handleAddCategory(callbackQuery);
} else if (action.startsWith('edit_category_')) {
logDebug(action, 'handleEditCategory');
await adminProductHandler.handleEditCategory(callbackQuery);
} else if (action.startsWith('prod_category_')) {
logDebug(action, 'handleCategorySelection');
await adminProductHandler.handleCategorySelection(callbackQuery);
} else if (action.startsWith('add_subcategory_')) {
logDebug(action, 'handleAddSubcategory');
await adminProductHandler.handleAddSubcategory(callbackQuery);
} else if (action.startsWith('prod_subcategory_')) {
logDebug(action, 'handleSubcategorySelection');
await adminProductHandler.handleSubcategorySelection(callbackQuery);
} else if (action.startsWith('add_product_')) {
logDebug(action, 'handleAddProduct');
await adminProductHandler.handleAddProduct(callbackQuery);
} else if (action.startsWith('view_product_')) {
logDebug(action, 'handleViewProduct');
await adminProductHandler.handleViewProduct(callbackQuery);
}
// Admin user management
else if (action.startsWith('view_user_')) {
logDebug(action, 'handleViewUser');
await adminUserHandler.handleViewUser(callbackQuery);
} else if (action.startsWith('delete_user_')) {
logDebug(action, 'handleDeleteUser');
await adminUserHandler.handleDeleteUser(callbackQuery);
} else if (action.startsWith('confirm_delete_user_')) {
logDebug(action, 'handleConfirmDelete');
await adminUserHandler.handleConfirmDelete(callbackQuery);
} else if (action.startsWith('edit_user_balance_')) {
logDebug(action, 'handleEditUserBalance');
await adminUserHandler.handleEditUserBalance(callbackQuery);
}
await bot.answerCallbackQuery(callbackQuery.id);
} catch (error) {
await ErrorHandler.handleError(bot, msg.chat.id, error, 'callback query');
}
});
// Error handling
bot.on('polling_error', ErrorHandler.handlePollingError);
process.on('unhandledRejection', (error) => {
console.error('Unhandled promise rejection:', error);
console.error('Unhandled promise rejection:', error);
});
console.log('Bot is running...');