Spaces:
Running
Running
| const { Telegraf, Markup } = require('telegraf'); | |
| const Product = require('../models/Product'); | |
| const Order = require('../models/Order'); | |
| const Category = require('../models/Category'); | |
| const Banner = require('../models/Banner'); | |
| const dns = require('dns'); | |
| const https = require('https'); | |
| const http = require('http'); | |
| const { GoogleGenerativeAI } = require('@google/generative-ai'); | |
| const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || ''); | |
| dns.setDefaultResultOrder('ipv4first'); | |
| // AI rasm yuklab olish (redirect'lar bilan) | |
| function downloadImage(url) { | |
| return new Promise((resolve, reject) => { | |
| const protocol = url.startsWith('https') ? https : http; | |
| const req = protocol.get(url, { timeout: 45000 }, (res) => { | |
| // Redirect bo'lsa β kuzatib borish | |
| if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { | |
| return downloadImage(res.headers.location).then(resolve).catch(reject); | |
| } | |
| if (res.statusCode !== 200) { | |
| return reject(new Error(`Status: ${res.statusCode}`)); | |
| } | |
| const chunks = []; | |
| res.on('data', chunk => chunks.push(chunk)); | |
| res.on('end', () => resolve(Buffer.concat(chunks))); | |
| res.on('error', reject); | |
| }); | |
| req.on('error', reject); | |
| req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); }); | |
| }); | |
| } | |
| // O'zbekcha-Inglizcha sodda lug'at (Gemini ishlamasa fallback) | |
| const uzToEn = { | |
| 'kiyim': 'clothing', 'kiyimlar': 'clothes', 'moda': 'fashion', 'ayol': 'woman', 'erkak': 'man', | |
| 'go\'zal': 'beautiful', 'chiroyli': 'beautiful', 'zamonaviy': 'modern', 'yangi': 'new', | |
| 'chegirma': 'sale discount', 'skidka': 'sale discount', 'aksiya': 'promotion sale', | |
| 'arzon': 'affordable price', 'narx': 'price', | |
| 'yozgi': 'summer', 'qishki': 'winter', 'bahorgi': 'spring', 'kuzgi': 'autumn', | |
| 'kolleksiya': 'collection', 'sport': 'sports athletic', 'sportiv': 'sports athletic', | |
| 'athietivk': 'athletic sportswear', 'atletik': 'athletic sportswear', | |
| 'texnika': 'technology gadgets', 'gadjet': 'gadgets devices', 'telefon': 'smartphone phone', | |
| 'kompyuter': 'computer laptop', 'audio': 'audio headphones', | |
| 'sovga': 'gift present', 'bayram': 'holiday celebration', 'tovar': 'product', 'tavaar': 'product', | |
| 'tovarlar': 'products', 'tavaarlar': 'products', 'barch': 'all', 'barcha': 'all', | |
| 'reklama': 'advertisement', 'banner': 'promotional banner', 'dizayn': 'design', | |
| 'dizayinda': 'in design style', 'premium': 'premium luxury', 'klassik': 'classic elegant', | |
| 'rangli': 'colorful', 'qora': 'black', 'oq': 'white', 'qizil': 'red', 'ko\'k': 'blue', | |
| 'yashil': 'green', 'sariq': 'yellow', 'pushti': 'pink', | |
| 'kurtka': 'jacket', 'kostyum': 'suit', 'kastiyum': 'suit', 'ko\'ylak': 'shirt dress', | |
| 'shim': 'pants trousers', 'futbolka': 't-shirt', 'palto': 'coat overcoat', | |
| 'tufli': 'shoes', 'krossovka': 'sneakers', 'sumka': 'bag handbag', | |
| 'bolalar': 'children kids', 'bola': 'child kid', 'oila': 'family', | |
| 'do\'kon': 'store shop', 'magazin': 'store shop', 'savdo': 'commerce shopping', | |
| 'yasa': '', 'yoq': '', 'deb': '', 'yozilgan': 'with text overlay', | |
| 'mantiya': 'graduation gown mantle', 'manti': 'graduation gown coat', | |
| }; | |
| function translateUzToEn(text) { | |
| let result = text.toLowerCase(); | |
| // Har bir so'zni tarjima qilish | |
| for (const [uz, en] of Object.entries(uzToEn)) { | |
| result = result.replace(new RegExp(uz.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), en); | |
| } | |
| // Raqamlarni saqlab qolish (masalan: 30%) | |
| return result.trim(); | |
| } | |
| // AI yordamida (Gemini) promptni professional kengaytirish | |
| async function enhancePromptWithGemini(userText, templateBase = '') { | |
| // Avval Gemini bilan urinib ko'rish | |
| if (process.env.GEMINI_API_KEY) { | |
| try { | |
| const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" }); | |
| const prompt = `You are an expert AI image prompt engineer for an e-commerce platform. | |
| The user wants to generate a banner image, but they write in Uzbek and might have typos. | |
| CRITICAL RULE: Interpret words in FASHION, CLOTHING, TECH, or E-COMMERCE contexts. E.g., if they write "manti", "mantiani", or "mantiya", they mean "graduation gown", "coat", or "mantle" (clothing), NEVER the food (dumplings). | |
| Step 1: Understand their intent and correct typos. | |
| Step 2: Convert the idea into a clean, highly descriptive English prompt for Midjourney/Flux. | |
| Step 3: Keep it heavily focused on the SUBJECT. DO NOT add generic tags like "banner" or "advertising" that ruin the immersion. Just describe the scene, the models, the clothes, and the environment. Add: ", photorealistic, cinematic, highly detailed, no text". | |
| Example Output: "A handsome male student and a beautiful female student wearing elegant graduation gowns, evening graduation party, cinematic lighting, photorealistic, no text" | |
| Template Context: ${templateBase || 'None'} | |
| User's Idea: "${userText}" | |
| Respond ONLY with the final English prompt string, and nothing else.`; | |
| const result = await model.generateContent(prompt); | |
| const enhanced = result.response.text().trim(); | |
| console.log('[AI BANNER] Gemini enhanced:', enhanced); | |
| return enhanced; | |
| } catch (e) { | |
| console.error("[AI BANNER] Gemini FAILED:", e.message); | |
| // Gemini xato qilsa β fallback'ga tushadi (pastga) | |
| } | |
| } else { | |
| console.warn("[AI BANNER] GEMINI_API_KEY not found, using dictionary fallback"); | |
| } | |
| // FALLBACK: Gemini ishlamasa, oddiy lug'at orqali tarjima | |
| const translated = translateUzToEn(userText); | |
| const base = templateBase ? templateBase + ', ' : ''; | |
| const fallback = `${base}${translated}, professional product photography, photorealistic, cinematic lighting, highly detailed`; | |
| console.log('[AI BANNER] Fallback prompt:', fallback); | |
| return fallback; | |
| } | |
| // AI Banner Shablon Promptlari | |
| const aiTemplates = { | |
| 'fashion': { | |
| label: 'π Kiyim/Moda', | |
| base: 'elegant fashion collection showcase, stylish models wearing designer clothing, luxury boutique atmosphere, soft studio lighting, fashion editorial photography, haute couture, magazine quality' | |
| }, | |
| 'tech': { | |
| label: 'π± Texnika', | |
| base: 'modern technology products showcase, sleek gadgets and devices, futuristic minimalist design, cool blue LED lighting, professional product photography, tech store display' | |
| }, | |
| 'holiday': { | |
| label: 'π Bayram/Sovga', | |
| base: 'festive celebration gift boxes, beautifully wrapped presents, warm holiday atmosphere, golden decorations, bokeh lights background, joyful celebration mood' | |
| }, | |
| 'sale': { | |
| label: 'π· Chegirma/Aksiya', | |
| base: 'exciting shopping sale promotion, vibrant colorful shopping bags, dynamic energy, confetti, excited shoppers, retail celebration atmosphere, bold vibrant colors' | |
| }, | |
| 'lifestyle': { | |
| label: 'πΏ Lifestyle', | |
| base: 'premium lifestyle photography, beautiful natural setting, warm golden hour lighting, elegant composition, aspirational mood, luxury brand aesthetic' | |
| }, | |
| 'sport': { | |
| label: 'β½ Sport', | |
| base: 'dynamic sports athletic photography, active lifestyle, energetic motion blur, fitness motivation, professional sports equipment, vibrant action shot' | |
| } | |
| }; | |
| let bot; | |
| const line = 'ββββββββββββββββββββββββββ'; | |
| const thinLine = 'β β β β β β β β β β β β β'; | |
| const formatPrice = (num) => Number(num).toLocaleString('uz-UZ'); | |
| const formatDate = (d) => { | |
| const date = new Date(d); | |
| return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; | |
| }; | |
| const getMainMenu = () => { | |
| return Markup.inlineKeyboard([ | |
| [Markup.button.callback('β Yangi tovar', 'action_addproduct'), Markup.button.callback('π¦ Tovarlar', 'action_products_0')], | |
| [Markup.button.callback('π Kategoriyalar', 'action_categories'), Markup.button.callback('π Qidirish', 'action_search')], | |
| [Markup.button.callback('π Barcha Buyurtmalar', 'action_orders_0'), Markup.button.callback('π Turniket (Chek O\'qish)', 'action_search_order')], | |
| [Markup.button.callback('π Statistika', 'action_stats'), Markup.button.callback('π Reklamalar', 'action_banners')], | |
| [Markup.button.callback('π Do\'kon Manzili', 'action_set_location'), Markup.button.callback('π₯ Excel', 'action_export_excel')], | |
| [Markup.button.callback('π’ Push Xabar', 'action_send_push'), Markup.button.callback('β Yordam', 'action_help')] | |
| ]); | |
| }; | |
| if (process.env.BOT_TOKEN && process.env.BOT_TOKEN !== 'YOUR_TELEGRAM_BOT_TOKEN') { | |
| bot = new Telegraf(process.env.BOT_TOKEN, { telegram: { apiRoot: 'https://api.telegram.org' } }); | |
| const TIMEOUT_MS = 30 * 60 * 1000; // 30 daqiqa | |
| const rawAppState = {}; | |
| const appState = new Proxy(rawAppState, { | |
| set(target, prop, value) { | |
| if (target[prop] && target[prop].timer) { | |
| clearTimeout(target[prop].timer); | |
| } | |
| if (value && typeof value === 'object') { | |
| value.timer = setTimeout(() => { | |
| delete target[prop]; | |
| try { | |
| bot.telegram.sendMessage(prop, 'β³ Uzoq vaqt harakatsizlik sababli joriy amaliyot xavfsiz bekor qilindi. Bosh menyudasiz.', { parse_mode: 'Markdown', ...getMainMenu() }); | |
| } catch(e) {} | |
| }, TIMEOUT_MS); | |
| } | |
| target[prop] = value; | |
| return true; | |
| }, | |
| deleteProperty(target, prop) { | |
| if (target[prop] && target[prop].timer) { | |
| clearTimeout(target[prop].timer); | |
| } | |
| delete target[prop]; | |
| return true; | |
| } | |
| }); | |
| const isAdmin = (ctx) => ctx.from.id.toString() === process.env.ADMIN_ID; | |
| bot.start(async (ctx) => { | |
| if (!isAdmin(ctx)) return ctx.reply('β οΈ Siz admin emassiz.'); | |
| delete appState[ctx.from.id]; | |
| try { | |
| const logoPath = require('path').join(__dirname, '../assets/mtextile_logo.png'); | |
| await ctx.replyWithPhoto({ source: logoPath }, { | |
| caption: `${line}\nπ *MTEXTILE ADMIN PANEL V4.0*\n${line}\n\nQuyidagi menyudan tanlang:`, | |
| parse_mode: 'Markdown', | |
| ...getMainMenu() | |
| }); | |
| } catch(e) { | |
| ctx.reply(`${line}\nπ *MTEXTILE ADMIN PANEL V4.0*\n${line}\n\nQuyidagi menyudan tanlang:`, { parse_mode: 'Markdown', ...getMainMenu() }); | |
| } | |
| }); | |
| // Istalgan paytda chala jarayonni bekor qilish | |
| bot.command('cancel', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const had = !!appState[ctx.from.id]; | |
| delete appState[ctx.from.id]; | |
| ctx.reply(had ? 'β Jarayon bekor qilindi.' : 'βΉοΈ Faol jarayon yo\'q.', getMainMenu()); | |
| }); | |
| bot.hears('β Bekor qilish', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| delete appState[ctx.from.id]; | |
| ctx.reply('β Bekor qilindi.', getMainMenu()); | |
| }); | |
| bot.action('action_home', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| delete appState[ctx.from.id]; | |
| try { ctx.deleteMessage(); } catch (e) {} | |
| ctx.reply(`${line}\nπ *ASOSIY MENYU*\n${line}`, { parse_mode: 'Markdown', ...getMainMenu() }); | |
| }); | |
| // ========================================== | |
| // KATEGORIYALAR BOSHQARUVI | |
| // ========================================== | |
| bot.action('action_categories', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| const categories = await Category.find().sort({ order: 1 }); | |
| let msg = `${line}\nπ *KATEGORIYALAR*\n${line}\n\n`; | |
| if (categories.length === 0) msg += `π Hozircha kategoriyalar yo'q.`; | |
| else { | |
| categories.forEach(c => { msg += `πΉ *${c.name}*\n`; }); | |
| } | |
| const buttons = [[Markup.button.callback('β Yangi kategoriya', 'action_addcategory')]]; | |
| categories.forEach(c => { | |
| buttons.push([ | |
| Markup.button.callback(`βοΈ ${c.name}`, `edit_cat_${c._id}`), | |
| Markup.button.callback(`π ${c.name}`, `del_cat_confirm_${c._id}`) | |
| ]); | |
| }); | |
| buttons.push([Markup.button.callback('π Menyu', 'action_home')]); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| bot.action('action_addcategory', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'adding_category' }; | |
| ctx.reply('βοΈ Yangi kategoriya nomini yozing (Masalan: Smartfonlar):', { parse_mode: 'Markdown', reply_markup: { force_reply: true } }); | |
| }); | |
| bot.action(/del_cat_confirm_(.+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const cId = ctx.match[1]; | |
| await ctx.answerCbQuery(); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| ctx.reply('β οΈ *Kategoriyani o\'chirmoqchimisiz?*\nUnga tegishli tovarlar o\'chmaydi, lekin kategoriyasi bo\'sh bo\'lib qoladi.', { | |
| parse_mode: 'Markdown', | |
| ...Markup.inlineKeyboard([[Markup.button.callback('β Ha, o\'chirish', `delcat_${cId}`), Markup.button.callback('β Yo\'q', 'action_categories')]]) | |
| }); | |
| }); | |
| bot.action(/delcat_(.+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| await Category.findByIdAndDelete(ctx.match[1]); | |
| ctx.answerCbQuery('Kategoriya o\'chirildi'); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| // Kategoriya ro'yxatini qayta ko'rsatish | |
| const categories = await Category.find().sort({ order: 1 }); | |
| let msg = `${line}\nπ *KATEGORIYALAR*\n${line}\n\n`; | |
| if (categories.length === 0) msg += 'π Hozircha kategoriyalar yo\'q.'; | |
| else categories.forEach(c => { msg += `πΉ *${c.name}*\n`; }); | |
| const buttons = [[Markup.button.callback('β Yangi kategoriya', 'action_addcategory')]]; | |
| categories.forEach(c => { | |
| buttons.push([ | |
| Markup.button.callback(`βοΈ ${c.name}`, `edit_cat_${c._id}`), | |
| Markup.button.callback(`π ${c.name}`, `del_cat_confirm_${c._id}`) | |
| ]); | |
| }); | |
| buttons.push([Markup.button.callback('π Menyu', 'action_home')]); | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| bot.action(/edit_cat_(.*)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'editing_category', catId: ctx.match[1] }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('βοΈ Kategoriya uchun yangi nom yozing:', { reply_markup: { force_reply: true } }); | |
| }); | |
| // ========================================== | |
| // TOVARLAR VA TO'LIQ TAHRIRLASH | |
| // ========================================== | |
| bot.action('action_addproduct', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'name' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('β *Yangi Tovar Qo\'shish*\n\nπ 1-qadam: Tovarning nomini yozing:', { parse_mode: 'Markdown' }); | |
| }); | |
| bot.action(/action_products_(\d+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const page = parseInt(ctx.match[1]); | |
| const limit = 2; // Keng tugmalar uchun kamroq limit | |
| const skip = page * limit; | |
| try { | |
| const productCount = await Product.countDocuments(); | |
| const products = await Product.find().sort({ createdAt: -1 }).skip(skip).limit(limit); | |
| if (products.length === 0) return ctx.answerCbQuery('π Tovar topilmadi.'); | |
| await ctx.answerCbQuery(); | |
| try { await ctx.deleteMessage(); } catch (e) {} | |
| await ctx.reply(`${line}\nπ¦ *TOVARLAR RO'YXATI* (${page + 1}-sahifa)\n${line}\nJami: *${productCount}* ta tovar`, { parse_mode: 'Markdown' }); | |
| for (const p of products) { | |
| const msg = `π· *${p.name}*\n${thinLine}\nπ Kat: \`${p.category}\`\nπ° Narx: *${formatPrice(p.price)} so'm*\nπ ${p.description || '-'}`; | |
| const buttons = [ | |
| [Markup.button.callback('βοΈ Nomi', `edit_pname_${p._id}`), Markup.button.callback('βοΈ Narx', `edit_price_${p._id}`)], | |
| [Markup.button.callback('π Tavsif', `edit_desc_${p._id}`), Markup.button.callback('π Kategoriya', `edit_pcat_${p._id}`)], | |
| [Markup.button.callback('πΈ Rasm', `edit_pimg_${p._id}`), Markup.button.callback('π Razmer', `edit_psize_${p._id}`)], | |
| [Markup.button.callback('π O\'chirish', `del_confirm_${p._id}`)] | |
| ]; | |
| if (p.imageUrl && p.imageUrl.startsWith('http')) { | |
| try { | |
| let photoSource = p.imageUrl; | |
| // Agar bizning proxy URL bo'lsa, Telegramning o'zining file_id sini ajratib olamiz | |
| if (p.imageUrl.includes('/api/image/')) { | |
| photoSource = p.imageUrl.split('/api/image/')[1]; | |
| } | |
| await ctx.replyWithPhoto(photoSource, { caption: msg, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch (err) { | |
| // Agar rasm xato qilsa (yo'q qolib ketsa), rasm o'rniga faqat text jo'natish | |
| await ctx.reply(msg + "\n\nβ οΈ (Rasm mavjud emas yoki xato)", { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } else { | |
| await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } | |
| const navButtons = []; | |
| if (page > 0) navButtons.push(Markup.button.callback('β¬ οΈ Oldingi', `action_products_${page - 1}`)); | |
| navButtons.push(Markup.button.callback(`π ${page + 1}/${Math.ceil(productCount / limit)}`, 'noop')); | |
| if (skip + limit < productCount) navButtons.push(Markup.button.callback('Keyingi β‘οΈ', `action_products_${page + 1}`)); | |
| await ctx.reply(`${thinLine}`, { ...Markup.inlineKeyboard([navButtons, [Markup.button.callback('π Menyu', 'action_home')]]) }); | |
| } catch (e) { ctx.reply('β Xato: ' + e.message); } | |
| }); | |
| bot.action(/edit_pname_(.*)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'edit_pname', pId: ctx.match[1] }; | |
| ctx.reply('Yangi nomni yozing:'); | |
| }); | |
| bot.action(/edit_price_(.*)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'editing_price', productId: ctx.match[1] }; | |
| ctx.reply('Yangi narxni yozing (faqat son):'); | |
| }); | |
| bot.action(/edit_desc_(.*)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'editing_desc', productId: ctx.match[1] }; | |
| ctx.reply('Yangi tavsif yozing:'); | |
| }); | |
| bot.action(/edit_pimg_(.*)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'edit_pimg', pId: ctx.match[1] }; | |
| ctx.reply('Yangi rasm yuboring yoki rasm linkini tashlang:'); | |
| }); | |
| bot.action(/edit_psize_(.*)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'edit_psize', pId: ctx.match[1] }; | |
| ctx.reply('π Razmerlarni vergul bilan yozing (Masalan: 44, 46, 48)\nYoki razmersiz qilish uchu "yoq" deb yozing:'); | |
| }); | |
| bot.action(/edit_pcat_(.*)/, async (ctx) => { | |
| const categories = await Category.find(); | |
| if(categories.length === 0) return ctx.reply('Kategoriyalar mavjud emas. Avval kategoriya yarating.'); | |
| appState[ctx.from.id] = { step: 'exec_edit_pcat', pId: ctx.match[1] }; | |
| const buttons = []; | |
| let row = []; | |
| categories.forEach((c, i) => { | |
| row.push(Markup.button.callback(c.name, `setpcat_${c.name}`)); | |
| if(row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; } | |
| }); | |
| ctx.reply('Qaysi kategoriyaga o\'zgartiramiz?', Markup.inlineKeyboard(buttons)); | |
| }); | |
| bot.action(/setpcat_(.+)/, async (ctx) => { | |
| const state = appState[ctx.from.id]; | |
| if(!state || state.step !== 'exec_edit_pcat') return; | |
| try { | |
| await Product.findByIdAndUpdate(state.pId, { category: ctx.match[1] }); | |
| ctx.reply('β Kategoriya yangilandi!', getMainMenu()); | |
| } catch(e){} | |
| delete appState[ctx.from.id]; | |
| }); | |
| bot.action(/del_confirm_(.*)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| ctx.reply('β οΈ *O\'chirmoqchimisiz?*', { parse_mode: 'Markdown', ...Markup.inlineKeyboard([[Markup.button.callback('β Ha', `del_product_${ctx.match[1]}`), Markup.button.callback('β Yo\'q', 'action_home')]]) }); | |
| }); | |
| bot.action(/del_product_(.*)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| await Product.findByIdAndDelete(ctx.match[1]); | |
| ctx.reply(`β O'chirildi.`, getMainMenu()); | |
| } catch (e) {} | |
| }); | |
| // ========================================== | |
| // BUYURTMALAR BOSHQAARUVI | |
| // ========================================== | |
| bot.action(/action_orders_(\d+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| delete appState[ctx.from.id]; | |
| const page = parseInt(ctx.match[1]); | |
| const limit = 3; | |
| const skip = page * limit; | |
| try { | |
| const orderCount = await Order.countDocuments(); | |
| const orders = await Order.find().sort({ createdAt: -1 }).skip(skip).limit(limit); | |
| if (orders.length === 0) return ctx.answerCbQuery('π Hozircha buyurtmalar yo\'q.'); | |
| await ctx.answerCbQuery(); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| await ctx.reply(`${line}\nπ *BUYURTMALAR* (${page+1}-sahifa)\n${line}\nJami: *${orderCount}* ta`, { parse_mode: 'Markdown' }); | |
| for (const o of orders) { | |
| let productsText = ""; | |
| o.products.forEach(p => { productsText += `β ${p.name} (${p.quantity} ta) \n`; }); | |
| let statusEmoji = o.status === 'Kutilmoqda' ? 'β³' : o.status === 'Xaridorga topshirildi' ? 'β ' : o.status === 'Olib ketishga tayyor' ? 'π' : 'π₯'; | |
| const msg = `π§Ύ *ID:* \`${o._id}\`\nπ€ Mijoz: *${o.customerName}*\nπ Tel: ${o.phone}\nπ Izoh: ${o.comment}\n\nπ *Tovarlar:*\n${productsText}\nπ° *Jami:* ${formatPrice(o.totalAmount)} so'm\nπ *Holati:* ${statusEmoji} ${o.status}\nπ Vaqt: ${formatDate(o.createdAt)}`; | |
| await ctx.reply(msg, { parse_mode: 'Markdown', ...orderStatusButtonsForNotify(o._id, o.status) }); | |
| } | |
| const navButtons = []; | |
| if (page > 0) navButtons.push(Markup.button.callback('β¬ οΈ', `action_orders_${page - 1}`)); | |
| navButtons.push(Markup.button.callback(`${page + 1}/${Math.ceil(orderCount / limit)}`, 'noop')); | |
| if (skip + limit < orderCount) navButtons.push(Markup.button.callback('β‘οΈ', `action_orders_${page + 1}`)); | |
| await ctx.reply(`${thinLine}`, { ...Markup.inlineKeyboard([navButtons, [Markup.button.callback('π Menyu', 'action_home')]]) }); | |
| } catch(e) { ctx.reply('Xatolik'); } | |
| }); | |
| bot.action(/order_status_(accept|ship|deliver|cancel)_(.*)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const action = ctx.match[1]; | |
| const orderId = ctx.match[2]; | |
| let newStatus = 'Kutilmoqda'; | |
| if (action === 'accept') newStatus = 'Yig\'ilmoqda'; | |
| if (action === 'ship') newStatus = 'Olib ketishga tayyor'; | |
| if (action === 'deliver') newStatus = 'Xaridorga topshirildi'; | |
| if (action === 'cancel') newStatus = 'Bekor qilindi'; | |
| try { | |
| await Order.findByIdAndUpdate(orderId, { status: newStatus }); | |
| ctx.answerCbQuery(`Holat: ${newStatus}`); | |
| // Xabardagi tugmalarni yangilab, tanlanganiga pichka qo'yish | |
| await ctx.editMessageReplyMarkup(orderStatusButtonsForNotify(orderId, newStatus).reply_markup); | |
| } catch(e) { ctx.answerCbQuery('Xato yuz berdi'); } | |
| }); | |
| // ========================================== | |
| // STATISTIKA & QIDIRUV | |
| // ========================================== | |
| bot.action('action_stats', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| delete appState[ctx.from.id]; | |
| try { | |
| const pCount = await Product.countDocuments(); | |
| const oCount = await Order.countDocuments(); | |
| const cCount = await Category.countDocuments(); | |
| // Jami tushumni hisoblash | |
| const orders = await Order.find({ status: { $ne: 'Bekor qilindi' } }); | |
| let totalMoney = 0; | |
| orders.forEach(o => totalMoney += o.totalAmount); | |
| const msg = `${line}\nπ *STATISTIKA VA HISOBOT*\n${line}\n\nπ¦ Jami tovarlar: *${pCount}*\nπ Kategoriyalar: *${cCount}*\nπ Barcha buyurtmalar: *${oCount}*\n\nπ° *Umumiy tushum:* ${formatPrice(totalMoney)} so'm`; | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard([[Markup.button.callback('π Menyu', 'action_home')]])}); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| bot.action('action_search', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'searching_product' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π *Qidirish*\n\nTovar nomini yozib yuboring (Masalan: "Kastiyum"):', { parse_mode: 'Markdown' }); | |
| }); | |
| bot.action('action_search_order', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'searching_order' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π *Turniket (Chek O\'qish)*\n\nMijoz ko\'rsatgan QR Koddagi 24 xonali ID raqamini yuboring:', { parse_mode: 'Markdown' }); | |
| }); | |
| bot.action('action_export_excel', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| ctx.answerCbQuery('π₯ Tayorlanmoqda...'); | |
| const products = await Product.find().sort({ category: 1, name: 1 }); | |
| if (products.length === 0) return ctx.reply('π Eksport qilish uchun tovar yo\'q.', getMainMenu()); | |
| let csv = 'Nomi,Kategoriya,Narx,Tavsif,Razmerlar\n'; | |
| products.forEach(p => { | |
| const sizes = p.sizes ? p.sizes.join('; ') : ''; | |
| const desc = (p.description || '').replace(/,/g, ' ').replace(/\n/g, ' '); | |
| csv += `"${p.name}","${p.category || ''}",${p.price},"${desc}","${sizes}"\n`; | |
| }); | |
| await ctx.replyWithDocument({ | |
| source: Buffer.from(csv, 'utf-8'), | |
| filename: `tovarlar_${new Date().toISOString().slice(0,10)}.csv` | |
| }, { caption: `π Jami ${products.length} ta tovar eksport qilindi.` }); | |
| } catch(e) { | |
| ctx.reply('β Xatolik: ' + e.message); | |
| } | |
| }); | |
| // Filter stub olib tashlandi | |
| bot.action('action_help', (ctx) => { | |
| ctx.answerCbQuery(); | |
| let msg = `β *YORDAM*\n\n` + | |
| `Quyidagi bo'limlar orqali do'konni to'liq boshqarasiz:\n\n` + | |
| `π¦ *Tovarlar* - Tahrirlash, O'chirish va Rasm o'zgartirish.\n` + | |
| `π *Kategoriyalar* - Guruhlar yaratish, nomini o'zgartirish.\n` + | |
| `π *Buyurtmalar* - Holatini (yig'ilmoqda, tayyor) tasdiqlash.\n` + | |
| `π *Qidirish* - Ismi bilan izlab topib tahrirlash.\n` + | |
| `π *Statistika* - Tushumlar va statistika.`; | |
| ctx.reply(msg, { parse_mode: 'Markdown' }); | |
| }); | |
| // ========================================== | |
| // π REKLAMA BANNERLARI β PREMIUM PANEL V2.0 | |
| // ========================================== | |
| bot.action('action_banners', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| delete appState[ctx.from.id]; | |
| try { | |
| const banners = await Banner.find().sort({ order: 1 }); | |
| // Muddati o'tganlarni avtomatik o'chirish | |
| const now = new Date(); | |
| for (const b of banners) { | |
| if (b.expiresAt && new Date(b.expiresAt) < now) { | |
| b.isActive = false; | |
| await b.save(); | |
| } | |
| } | |
| const activeBanners = banners.filter(b => b.isActive); | |
| let msg = `${line}\nπ *REKLAMA BANNERLARI*\n${line}\n\n`; | |
| if (activeBanners.length === 0) { | |
| msg += `π Aktiv bannerlar yo'q.\n\nπ‘ _Quyidagi tugmalar orqali yangi banner qo'shing:_`; | |
| } else { | |
| msg += `β *${activeBanners.length}* ta aktiv banner\n\n`; | |
| activeBanners.forEach((b, i) => { | |
| const titleStr = b.title ? b.title : '(Nomi yo\'q)'; | |
| const linkStr = b.linkType === 'none' ? 'β' : | |
| b.linkType === 'category' ? `π ${b.linkValue}` : | |
| b.linkType === 'product' ? `π¦ ${b.linkValue}` : | |
| `π ${b.linkValue}`; | |
| const expStr = b.expiresAt ? formatDate(b.expiresAt) : 'βΎ Muddatsiz'; | |
| msg += `*${i + 1}.* ${titleStr}\n β³ ${linkStr} | ${expStr}\n\n`; | |
| }); | |
| } | |
| const buttons = [ | |
| [Markup.button.callback('β Rasm yuklash', 'banner_add_photo'), Markup.button.callback('π¨ AI yaratish', 'banner_ai_menu')] | |
| ]; | |
| activeBanners.forEach((b, index) => { | |
| buttons.push([ | |
| Markup.button.callback(`πΈ #${index + 1} ko'rish`, `banner_view_${b._id}`), | |
| Markup.button.callback(`βοΈ Tahrirlash`, `banner_edit_${b._id}`), | |
| Markup.button.callback(`π`, `banner_del_confirm_${b._id}`) | |
| ]); | |
| }); | |
| if (activeBanners.length > 1) { | |
| buttons.push([Markup.button.callback('π Tartibni o\'zgartirish', 'banner_reorder')]); | |
| } | |
| buttons.push([Markup.button.callback('π Menyu', 'action_home')]); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato: ' + e.message); } | |
| }); | |
| // πΈ Banner ko'rish yoki tahrirlash (rasmli preview) | |
| bot.action(/banner_(view|edit)_(.+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| const bannerId = ctx.match[2]; | |
| const banner = await Banner.findById(bannerId); | |
| if (!banner) return ctx.answerCbQuery('Banner topilmadi'); | |
| await ctx.answerCbQuery(); | |
| try { await ctx.deleteMessage(); } catch(e){} | |
| const titleStr = banner.title || '(Nomi yo\'q)'; | |
| const subtitleStr = banner.subtitle || 'β'; | |
| const linkStr = banner.linkType === 'none' ? 'Havolasiz' : | |
| `${banner.linkType}: ${banner.linkValue}`; | |
| const expStr = banner.expiresAt ? formatDate(banner.expiresAt) : 'Muddatsiz'; | |
| const statusStr = banner.isActive ? 'β Faol' : 'βΈ O\'chirilgan'; | |
| const caption = `π *BANNER TAFSILOTLARI*\n${line}\n\nπ *Sarlavha:* ${titleStr}\nπ *Matn:* ${subtitleStr}\nπ *Havola:* ${linkStr}\nπ *Muddat:* ${expStr}\nπ *Holat:* ${statusStr}`; | |
| const buttons = [ | |
| [Markup.button.callback('βοΈ Sarlavha', `banner_set_title_${banner._id}`), Markup.button.callback('π Matn', `banner_set_subtitle_${banner._id}`)], | |
| [Markup.button.callback('π Havola', `banner_set_link_${banner._id}`), Markup.button.callback('π Muddat', `banner_set_expire_${banner._id}`)], | |
| [Markup.button.callback('π Orqaga', 'action_banners')] | |
| ]; | |
| if (banner.imageUrl && banner.imageUrl.startsWith('http')) { | |
| try { | |
| let photoSource = banner.imageUrl; | |
| if (photoSource.includes('/api/image/')) photoSource = photoSource.split('/api/image/')[1]; | |
| await ctx.replyWithPhoto(photoSource, { caption, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { | |
| await ctx.reply(caption + '\n\nβ οΈ (Rasm yuklanmadi)', { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } else { | |
| await ctx.reply(caption, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| // βοΈ Banner tahrirlash β Sarlavha | |
| bot.action(/banner_set_title_(.+)/, (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'banner_edit_title', bannerId: ctx.match[1] }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π Banner uchun yangi *sarlavha* yozing:\n\n_Masalan: "Yozgi Chegirma 50%"_', { parse_mode: 'Markdown' }); | |
| }); | |
| // βοΈ Banner tahrirlash β Subtitle | |
| bot.action(/banner_set_subtitle_(.+)/, (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'banner_edit_subtitle', bannerId: ctx.match[1] }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π Banner uchun *qo\'shimcha matn* yozing:\n\n_Masalan: "Barcha kiyimlarga amal qiladi"_\n\nO\'tkazish uchun "yoq" deb yozing.', { parse_mode: 'Markdown' }); | |
| }); | |
| // π Banner tahrirlash β Link | |
| bot.action(/banner_set_link_(.+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const bannerId = ctx.match[1]; | |
| ctx.answerCbQuery(); | |
| const categories = await Category.find().sort({ order: 1 }); | |
| const buttons = [ | |
| [Markup.button.callback('β Havolasiz', `banner_link_none_${bannerId}`)] | |
| ]; | |
| let row = []; | |
| categories.forEach((c, i) => { | |
| row.push(Markup.button.callback(`π ${c.name}`, `banner_link_cat_${bannerId}_${c.name}`)); | |
| if (row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; } | |
| }); | |
| buttons.push([Markup.button.callback('π Tashqi URL', `banner_link_url_${bannerId}`)]); | |
| buttons.push([Markup.button.callback('π Orqaga', `banner_view_${bannerId}`)]); | |
| ctx.reply('π *Banner havolasini tanlang:*\n\nFoydalanuvchi bannerni bosganda qayerga yo\'naltirilsin?', { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| }); | |
| bot.action(/banner_link_none_(.+)/, async (ctx) => { | |
| await Banner.findByIdAndUpdate(ctx.match[1], { linkType: 'none', linkValue: '' }); | |
| ctx.answerCbQuery('β Havola olib tashlandi'); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| }); | |
| bot.action(/banner_link_cat_([^_]+)_(.+)/, async (ctx) => { | |
| const bannerId = ctx.match[1]; | |
| const catName = ctx.match[2]; | |
| await Banner.findByIdAndUpdate(bannerId, { linkType: 'category', linkValue: catName }); | |
| ctx.answerCbQuery(`β Havola: ${catName} kategoriyasi`); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| }); | |
| bot.action(/banner_link_url_(.+)/, (ctx) => { | |
| appState[ctx.from.id] = { step: 'banner_edit_link_url', bannerId: ctx.match[1] }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π Tashqi URL manzilini yozing:\n\n_Masalan: https://example.com_', { parse_mode: 'Markdown' }); | |
| }); | |
| // π Banner tahrirlash β Muddat | |
| bot.action(/banner_set_expire_(.+)/, (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'banner_edit_expire', bannerId: ctx.match[1] }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π Banner tugash sanasini yozing:\n\n_Format: KK.OO.YYYY (masalan: 01.06.2026)_\n\nMuddatsiz qilish uchun "yoq" deb yozing.', { parse_mode: 'Markdown' }); | |
| }); | |
| // π Tartibni o'zgartirish | |
| bot.action('banner_reorder', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| try { | |
| const banners = await Banner.find({ isActive: true }).sort({ order: 1 }); | |
| if (banners.length < 2) return ctx.answerCbQuery('Kamida 2 ta banner kerak'); | |
| let msg = `π *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`; | |
| const buttons = []; | |
| banners.forEach((b, i) => { | |
| const titleStr = b.title || `Banner ${i + 1}`; | |
| msg += `*${i + 1}.* ${titleStr}\n`; | |
| const row = []; | |
| if (i > 0) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_moveup_${b._id}`)); | |
| if (i < banners.length - 1) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_movedn_${b._id}`)); | |
| if (row.length > 0) buttons.push(row); | |
| }); | |
| buttons.push([Markup.button.callback('π Orqaga', 'action_banners')]); | |
| await ctx.answerCbQuery(); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| bot.action(/banner_moveup_(.+)/, async (ctx) => { | |
| try { | |
| const banners = await Banner.find({ isActive: true }).sort({ order: 1 }); | |
| const idx = banners.findIndex(b => b._id.toString() === ctx.match[1]); | |
| if (idx > 0) { | |
| const tempOrder = banners[idx].order; | |
| banners[idx].order = banners[idx - 1].order; | |
| banners[idx - 1].order = tempOrder; | |
| await banners[idx].save(); | |
| await banners[idx - 1].save(); | |
| } | |
| ctx.answerCbQuery('β¬οΈ Yuqoriga ko\'tarildi'); | |
| // Refreshing banner list | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| // Re-trigger reorder view | |
| const updatedBanners = await Banner.find({ isActive: true }).sort({ order: 1 }); | |
| let msg = `π *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`; | |
| const buttons = []; | |
| updatedBanners.forEach((b, i) => { | |
| msg += `*${i + 1}.* ${b.title || 'Banner ' + (i+1)}\n`; | |
| const row = []; | |
| if (i > 0) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_moveup_${b._id}`)); | |
| if (i < updatedBanners.length - 1) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_movedn_${b._id}`)); | |
| if (row.length > 0) buttons.push(row); | |
| }); | |
| buttons.push([Markup.button.callback('π Orqaga', 'action_banners')]); | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| bot.action(/banner_movedn_(.+)/, async (ctx) => { | |
| try { | |
| const banners = await Banner.find({ isActive: true }).sort({ order: 1 }); | |
| const idx = banners.findIndex(b => b._id.toString() === ctx.match[1]); | |
| if (idx < banners.length - 1) { | |
| const tempOrder = banners[idx].order; | |
| banners[idx].order = banners[idx + 1].order; | |
| banners[idx + 1].order = tempOrder; | |
| await banners[idx].save(); | |
| await banners[idx + 1].save(); | |
| } | |
| ctx.answerCbQuery('β¬οΈ Pastga tushirildi'); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| const updatedBanners = await Banner.find({ isActive: true }).sort({ order: 1 }); | |
| let msg = `π *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`; | |
| const buttons = []; | |
| updatedBanners.forEach((b, i) => { | |
| msg += `*${i + 1}.* ${b.title || 'Banner ' + (i+1)}\n`; | |
| const row = []; | |
| if (i > 0) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_moveup_${b._id}`)); | |
| if (i < updatedBanners.length - 1) row.push(Markup.button.callback(`β¬οΈ ${i + 1}`, `banner_movedn_${b._id}`)); | |
| if (row.length > 0) buttons.push(row); | |
| }); | |
| buttons.push([Markup.button.callback('π Orqaga', 'action_banners')]); | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| }); | |
| // β Yangi banner qo'shish (rasm yuklash) | |
| bot.action('banner_add_photo', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'banner_wizard_photo' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply(`πΈ *YANGI BANNER QO'SHISH* (1/4)\n${thinLine}\n\nπΌ Rasm yuboring (Landscape / Yotqizilgan format tavsiya etiladi):`, { parse_mode: 'Markdown' }); | |
| }); | |
| // π Banner o'chirish β Tasdiqlash | |
| bot.action(/banner_del_confirm_(.+)/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const bannerId = ctx.match[1]; | |
| console.log('[BANNER DELETE] Confirm requested for:', bannerId); | |
| try { await ctx.answerCbQuery(); } catch(e) {} | |
| try { await ctx.deleteMessage(); } catch(e) {} | |
| await ctx.reply('β οΈ *Bannerni o\'chirmoqchimisiz?*\n\nBu amalni ortga qaytarib bo\'lmaydi.', { | |
| parse_mode: 'Markdown', | |
| ...Markup.inlineKeyboard([ | |
| [Markup.button.callback('β Ha, o\'chirish', `bdel_${bannerId}`), Markup.button.callback('β Yo\'q', 'action_banners')] | |
| ]) | |
| }); | |
| }); | |
| // π Banner o'chirish β Yakuniy bajarish (ikkala nom ham ishlaydi) | |
| async function executeBannerDelete(ctx, bannerId) { | |
| console.log('[BANNER DELETE] Executing for:', bannerId); | |
| try { | |
| const result = await Banner.findByIdAndDelete(bannerId); | |
| console.log('[BANNER DELETE] Result:', result ? 'OK Deleted' : 'Not found in DB'); | |
| try { await ctx.answerCbQuery('β O\'chirildi!'); } catch(e) {} | |
| try { await ctx.deleteMessage(); } catch(e) {} | |
| await ctx.reply('β Banner muvaffaqiyatli o\'chirildi!', getMainMenu()); | |
| } catch(e) { | |
| console.error('[BANNER DELETE] DB Error:', e.message); | |
| try { await ctx.answerCbQuery('β Xato'); } catch(e2) {} | |
| await ctx.reply('β Xatolik: ' + e.message, getMainMenu()); | |
| } | |
| } | |
| bot.action(/^bdel_(.+)$/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| await executeBannerDelete(ctx, ctx.match[1]); | |
| }); | |
| bot.action(/^banner_del_exec_(.+)$/, async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| await executeBannerDelete(ctx, ctx.match[1]); | |
| }); | |
| // ========================================== | |
| // π¨ AI BANNER YARATISH β PREMIUM V2.0 | |
| // ========================================== | |
| bot.action('banner_ai_menu', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| ctx.answerCbQuery(); | |
| const buttons = []; | |
| const templateKeys = Object.keys(aiTemplates); | |
| let row = []; | |
| templateKeys.forEach((key, i) => { | |
| row.push(Markup.button.callback(aiTemplates[key].label, `ai_tpl_${key}`)); | |
| if (row.length === 2 || i === templateKeys.length - 1) { buttons.push(row); row = []; } | |
| }); | |
| buttons.push([Markup.button.callback('βοΈ Erkin yozish', 'ai_free_prompt')]); | |
| buttons.push([Markup.button.callback('π Orqaga', 'action_banners')]); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| ctx.reply(`π¨ *AI BANNER YARATISH*\n${line}\n\nQanday turdagi banner kerak?\nShablon tanlang yoki erkin yozing:`, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| }); | |
| // Shablon tanlanganda | |
| bot.action(/ai_tpl_(.+)/, (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const templateKey = ctx.match[1]; | |
| const template = aiTemplates[templateKey]; | |
| if (!template) return ctx.answerCbQuery('Shablon topilmadi'); | |
| appState[ctx.from.id] = { step: 'ai_template_prompt', templateKey, templateBase: template.base }; | |
| ctx.answerCbQuery(); | |
| ctx.reply(`π¨ *${template.label} shabloni tanlandi!*\n\nEndi qo'shimcha tavsif bering (o'zbekchada):\n\n_Masalan: "chiroyli qizil kiyimlar, yozgi kolleksiya"_\n\nπ‘ _Yoki batafsil yozmang β shunchaki_ "davom" _deb yozing_`, { parse_mode: 'Markdown' }); | |
| }); | |
| // Erkin prompt | |
| bot.action('ai_free_prompt', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'ai_free_prompt_input' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply(`βοΈ *ERKIN AI BANNER*\n${thinLine}\n\nRasmda nima bo'lishini o'zbekcha yoki inglizcha batafsil yozing:\n\n_"Kiyimlar chegirmasi, yozgi aksiya"_\n_"Yangi yil sovg'alari, bayram kayfiyati"_\n_"Go'zal ayollar kiyimlari, zamonaviy moda"_\n\nπ‘ _Qancha batafsil yozsangiz, shuncha sifatli rasm!_`, { parse_mode: 'Markdown' }); | |
| }); | |
| // AI rasmni 2 variantda yaratish funksiyasi (ENG KUCHLI BEPUL MODELLAR) | |
| async function generateAIBannerVariants(ctx, finalPrompt, originalPrompt) { | |
| const userId = ctx.from.id; | |
| const ts1 = Date.now(); | |
| const ts2 = ts1 + 12345; | |
| const encoded = encodeURIComponent(finalPrompt); | |
| // 2026 yildagi eng kuchli bepul modellar (Pollinations orqali): | |
| // Variant 1: GPT Image (OpenAI DALL-E darajasi β eng sifatli) | |
| // Variant 2: Seedream5 (Google DeepMind β fotorealistik) | |
| const url1 = `https://image.pollinations.ai/prompt/${encoded}?width=1024&height=430&seed=${ts1}&nologo=true&model=gptimage`; | |
| const url2 = `https://image.pollinations.ai/prompt/${encoded}?width=1024&height=430&seed=${ts2}&nologo=true&model=seedream5`; | |
| try { | |
| await ctx.reply('β³ *2 ta super model* ishga tushmoqda...\n\nπΉ GPT Image (OpenAI)\nπΉ Seedream5 (Google)\n\n_Kuting, 20-60 soniya..._', { parse_mode: 'Markdown' }); | |
| // Ikkalasini xavfsiz yuklab olish qotib qolmasligi uchun biroz kutamiz (stagger resquests) | |
| let res1, res2; | |
| try { res1 = await downloadImage(url1); } catch (err) { res1 = null; console.error("URL1 fail:", err); } | |
| await new Promise(r => setTimeout(r, 1000)); // 1 soniya pauza | |
| try { res2 = await downloadImage(url2); } catch (err) { res2 = null; console.error("URL2 fail:", err); } | |
| let msg1, msg2; | |
| let fileId1 = null, fileId2 = null; | |
| // 1-variant tekshiriladi | |
| if (res1) { | |
| msg1 = await ctx.replyWithPhoto({ source: res1, filename: 'variant1.jpg' }, { | |
| caption: `π¨ *Variant 1 β GPT Image (OpenAI)*\nπ _"${originalPrompt}"_`, | |
| parse_mode: 'Markdown', | |
| ...Markup.inlineKeyboard([[Markup.button.callback('β Shu rasmni tanlash', 'ai_pick_1')]]) | |
| }); | |
| fileId1 = msg1.photo[msg1.photo.length - 1].file_id; | |
| } else { | |
| await ctx.reply('β οΈ Variant 1 ni yuklab olishda serverda xatolik yuz berdi.'); | |
| } | |
| // 2-variant tekshiriladi | |
| if (res2) { | |
| msg2 = await ctx.replyWithPhoto({ source: res2, filename: 'variant2.jpg' }, { | |
| caption: `π¨ *Variant 2 β Seedream5 (Google)*\nπ _"${originalPrompt}"_`, | |
| parse_mode: 'Markdown', | |
| ...Markup.inlineKeyboard([[Markup.button.callback('β Shu rasmni tanlash', 'ai_pick_2')]]) | |
| }); | |
| fileId2 = msg2.photo[msg2.photo.length - 1].file_id; | |
| } else { | |
| await ctx.reply('β οΈ Variant 2 ni yuklab olishda serverda xatolik yuz berdi.'); | |
| } | |
| if (!fileId1 && !fileId2) { | |
| throw new Error("Ikkala rasm ham yuklanmadi. Iltimos, qayta urining."); | |
| } | |
| appState[userId] = { | |
| step: 'ai_picking_variant', | |
| lastPrompt: originalPrompt, | |
| finalPrompt, | |
| fileId1, fileId2 | |
| }; | |
| await ctx.reply('Qaysi variantni tanlaysiz? Yoki qayta yarating:', { | |
| ...Markup.inlineKeyboard([ | |
| [Markup.button.callback('π Qayta yaratish (2 variant)', 'ai_regenerate_v2')], | |
| [Markup.button.callback('β Bekor qilish', 'action_banners')] | |
| ]) | |
| }); | |
| } catch(e) { | |
| ctx.reply('β AI rasm yaratishda xatolik: ' + e.message + '\nQayta urinib ko\'ring.', getMainMenu()); | |
| delete appState[userId]; | |
| } | |
| } | |
| // Variant tanlash | |
| bot.action('ai_pick_1', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[ctx.from.id]; | |
| if (!state || !state.fileId1) return ctx.answerCbQuery('Variant topilmadi'); | |
| await saveAIBannerFromFileId(ctx, state.fileId1, state.lastPrompt); | |
| }); | |
| bot.action('ai_pick_2', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[ctx.from.id]; | |
| if (!state || !state.fileId2) return ctx.answerCbQuery('Variant topilmadi'); | |
| await saveAIBannerFromFileId(ctx, state.fileId2, state.lastPrompt); | |
| }); | |
| // AI rasmni file_id orqali saqlash (TO'G'RI USUL) | |
| async function saveAIBannerFromFileId(ctx, fileId, title) { | |
| try { | |
| const imgUrl = `https://ibrohm-savdobotadmin.hf.space/api/image/${fileId}`; | |
| const bannerCount = await Banner.countDocuments({ isActive: true }); | |
| await new Banner({ | |
| imageUrl: imgUrl, | |
| title: title || '', | |
| order: bannerCount, | |
| isActive: true | |
| }).save(); | |
| ctx.answerCbQuery('β Saqlandi!'); | |
| try { await ctx.deleteMessage(); } catch(e) {} | |
| ctx.reply(`β AI banner saqlandi va ilovada ko'rinadi!\n\nπ _Sarlavha, havola va muddatni "π Reklamalar" bo'limidan tahrirlashingiz mumkin._`, { parse_mode: 'Markdown', ...getMainMenu() }); | |
| } catch(e) { ctx.answerCbQuery('Xato: ' + e.message); } | |
| delete appState[ctx.from.id]; | |
| } | |
| // Qayta yaratish (2 variant) | |
| bot.action('ai_regenerate_v2', async (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[ctx.from.id]; | |
| if (state && state.finalPrompt) { | |
| ctx.answerCbQuery('π Qayta yaratilmoqda...'); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| await generateAIBannerVariants(ctx, state.finalPrompt, state.lastPrompt); | |
| } else { | |
| ctx.answerCbQuery('Avval tavsif yozing'); | |
| } | |
| }); | |
| // Eski ai_regenerate va ai_save_last funksiyalari xavfsizlik va optimizatsiya maqsadida o'chirildi (V3.6) | |
| // ========================================== | |
| // MATN XABARLARI | |
| // ========================================== | |
| bot.on('text', async (ctx) => { | |
| const userId = ctx.from.id; | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[userId]; | |
| if (!state) return; | |
| const text = ctx.message.text; | |
| // Katgeoriya edit/add | |
| if (state.step === 'adding_category') { | |
| try { | |
| await new Category({ name: text }).save(); | |
| ctx.reply(`β *${text}* kategoriyasi qo'shildi!`, { parse_mode: 'Markdown', ...getMainMenu() }); | |
| } catch(e) { ctx.reply('Xato (ehtimol oldin qo\'shilgan)'); } | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'editing_category') { | |
| try { | |
| await Category.findByIdAndUpdate(state.catId, { name: text }); | |
| ctx.reply(`β Kategoriya yangilandi!`, getMainMenu()); | |
| } catch(e) {} | |
| delete appState[userId]; return; | |
| } | |
| // ββββββ B2C Kassir Qidiruv (Variant 2) ββββββ | |
| if (state.step === 'searching_order') { | |
| try { | |
| const searchTxt = text.trim(); | |
| let order = null; | |
| // Mongoose ObjectId orqali qidirish (24 hex characters) | |
| if (/^[0-9a-fA-F]{24}$/.test(searchTxt)) { | |
| order = await Order.findById(searchTxt); | |
| } | |
| // Agar qisqa qidiruv bo'lsa | |
| if (!order) { | |
| const match = await Order.find({ _id: { $regex: searchTxt, $options: 'i' } }).limit(1); | |
| if (match && match.length > 0) order = match[0]; | |
| } | |
| if (!order) { | |
| ctx.reply('β Buyurtma topilmadi. Raqamni tekshirib qayta yuboring:', { reply_markup: { force_reply: true } }); | |
| return; // Return so they can try again without dropping state | |
| } | |
| let productsText = ""; | |
| order.products.forEach(p => { | |
| productsText += `β ${p.name} (${p.quantity} ta) x ${formatPrice(p.price)}\n`; | |
| }); | |
| const statusEmoji = order.status === 'Kutilmoqda' ? 'β³' : order.status === 'Xaridorga topshirildi' ? 'β ' : order.status === 'Olib ketishga tayyor' ? 'π' : 'π₯'; | |
| const msg = `π§Ύ *TOPILDI β ID:* \`${order._id}\`\n${thinLine}\n` + | |
| `π€ Mijoz: *${order.customerName}*\nπ Tel: ${order.phone}\n\nπ *Tovarlar:*\n${productsText}\n` + | |
| `π° *Jami summa:* ${formatPrice(order.totalAmount)} so'm\n\n` + | |
| `Hozirgi holati: ${statusEmoji} ${order.status}\n\n` + | |
| `π³ *XARIDOR TO'LOV QILDIMI?*`; | |
| const buttons = [ | |
| [Markup.button.callback('β Pul Olindi (Yopish)', `order_status_deliver_${order._id}`)], | |
| [Markup.button.callback('β Bekor Qilish', `order_status_cancel_${order._id}`)], | |
| [Markup.button.callback('π Menyu', 'action_home')] | |
| ]; | |
| ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch (e) { | |
| ctx.reply('Xatolik yuz berdi: ' + e.message, getMainMenu()); | |
| } | |
| delete appState[userId]; return; | |
| } | |
| // Mahsulot edit | |
| if (state.step === 'editing_price') { | |
| const num = Number(text); | |
| if (!isNaN(num)) { | |
| await Product.findByIdAndUpdate(state.productId, { price: num }); | |
| ctx.reply('β Narx yangilandi', getMainMenu()); | |
| } | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'edit_pname') { | |
| await Product.findByIdAndUpdate(state.pId, { name: text }); | |
| ctx.reply('β Nom yangilandi', getMainMenu()); | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'editing_desc') { | |
| await Product.findByIdAndUpdate(state.productId, { description: text }); | |
| ctx.reply('β Tavsif yangilandi', getMainMenu()); | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'edit_pimg') { | |
| await Product.findByIdAndUpdate(state.pId, { imageUrl: text === 'yoq' ? '' : text }); | |
| ctx.reply('β Rasm URL yangilandi', getMainMenu()); | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'edit_psize') { | |
| let sizes = []; | |
| if (text.toLowerCase() !== 'yoq') { | |
| sizes = text.split(',').map(s => s.trim()).filter(s => s.length > 0); | |
| } | |
| await Product.findByIdAndUpdate(state.pId, { sizes: sizes }); | |
| ctx.reply('β Razmerlar yangilandi', getMainMenu()); | |
| delete appState[userId]; return; | |
| } | |
| // Banner tahrirlash β Sarlavha | |
| if (state.step === 'banner_edit_title') { | |
| try { | |
| await Banner.findByIdAndUpdate(state.bannerId, { title: text }); | |
| ctx.reply('β Sarlavha yangilandi!', getMainMenu()); | |
| } catch(e) { ctx.reply('Xato'); } | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'banner_edit_subtitle') { | |
| try { | |
| const val = text.toLowerCase() === 'yoq' ? '' : text; | |
| await Banner.findByIdAndUpdate(state.bannerId, { subtitle: val }); | |
| ctx.reply('β Matn yangilandi!', getMainMenu()); | |
| } catch(e) { ctx.reply('Xato'); } | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'banner_edit_link_url') { | |
| try { | |
| await Banner.findByIdAndUpdate(state.bannerId, { linkType: 'url', linkValue: text }); | |
| ctx.reply('β Havola yangilandi!', getMainMenu()); | |
| } catch(e) { ctx.reply('Xato'); } | |
| delete appState[userId]; return; | |
| } | |
| if (state.step === 'banner_edit_expire') { | |
| try { | |
| if (text.toLowerCase() === 'yoq') { | |
| await Banner.findByIdAndUpdate(state.bannerId, { expiresAt: null }); | |
| ctx.reply('β Muddat olib tashlandi (muddatsiz).', getMainMenu()); | |
| } else { | |
| const parts = text.split('.'); | |
| if (parts.length === 3) { | |
| const date = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0])); | |
| await Banner.findByIdAndUpdate(state.bannerId, { expiresAt: date }); | |
| ctx.reply(`β Muddat belgilandi: ${text}`, getMainMenu()); | |
| } else { | |
| ctx.reply('β Noto\'g\'ri format. KK.OO.YYYY (masalan: 01.06.2026)', getMainMenu()); | |
| } | |
| } | |
| } catch(e) { ctx.reply('Xato'); } | |
| delete appState[userId]; return; | |
| } | |
| // Banner wizard β sarlavha (2/4 qadam) | |
| if (state.step === 'banner_wizard_title') { | |
| state.bannerTitle = text; | |
| state.step = 'banner_wizard_link'; | |
| const categories = await Category.find().sort({ order: 1 }); | |
| const buttons = [ | |
| [Markup.button.callback('β Havolasiz', 'bwiz_link_none')] | |
| ]; | |
| let row = []; | |
| categories.forEach((c, i) => { | |
| row.push(Markup.button.callback(`π ${c.name}`, `bwiz_link_cat_${c.name}`)); | |
| if (row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; } | |
| }); | |
| buttons.push([Markup.button.callback('π Tashqi URL', 'bwiz_link_url')]); | |
| ctx.reply(`πΈ *YANGI BANNER* (3/4)\n${thinLine}\n\nπ Havola turini tanlang:`, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| return; | |
| } | |
| // Banner wizard β URL kiritish | |
| if (state.step === 'banner_wizard_url') { | |
| state.bannerLinkType = 'url'; | |
| state.bannerLinkValue = text; | |
| // Saqlash | |
| try { | |
| const bannerCount = await Banner.countDocuments({ isActive: true }); | |
| await new Banner({ | |
| imageUrl: state.bannerImageUrl, | |
| title: state.bannerTitle || '', | |
| linkType: state.bannerLinkType || 'none', | |
| linkValue: state.bannerLinkValue || '', | |
| order: bannerCount, | |
| isActive: true | |
| }).save(); | |
| ctx.reply('β Yangi banner saqlandi va ilovada ko\'rinadi!', getMainMenu()); | |
| } catch(e) { ctx.reply('Xato: ' + e.message); } | |
| delete appState[userId]; return; | |
| } | |
| // AI Banner β Shablon bilan | |
| if (state.step === 'ai_template_prompt') { | |
| try { | |
| const userText = text.toLowerCase() === 'davom' ? '' : text; | |
| await ctx.reply('π§ Gemini loyihangizni anglab, mukammal prompt tuzmoqda...'); | |
| const finalPrompt = await enhancePromptWithGemini(userText, state.templateBase); | |
| appState[userId] = { step: 'ai_generating', lastPrompt: text, templateBase: state.templateBase, finalPrompt }; | |
| await generateAIBannerVariants(ctx, finalPrompt, text || aiTemplates[state.templateKey]?.label || 'AI Banner'); | |
| } catch (e) { | |
| console.error("ai_template_prompt error:", e); | |
| ctx.reply('β Kechirasiz, tarmoqda uzilish yuz berdi. Iltimos qayta urining.', getMainMenu()); | |
| delete appState[userId]; | |
| } | |
| return; | |
| } | |
| // AI Banner β Erkin yozish | |
| if (state.step === 'ai_free_prompt_input') { | |
| try { | |
| await ctx.reply('π§ Gemini sizning fikringiz asosida mukammal prompt tuzmoqda...'); | |
| const finalPrompt = await enhancePromptWithGemini(text); | |
| appState[userId] = { step: 'ai_generating', lastPrompt: text, finalPrompt }; | |
| await generateAIBannerVariants(ctx, finalPrompt, text); | |
| } catch (e) { | |
| console.error("ai_free_prompt_input error:", e); | |
| ctx.reply('β Kechirasiz, tarmoqda xatolik yuz berdi. Iltimos qayta urining.', getMainMenu()); | |
| delete appState[userId]; | |
| } | |
| return; | |
| } | |
| // Qidiruv | |
| if (state.step === 'searching_product') { | |
| try { | |
| const results = await Product.find({ name: { $regex: text, $options: 'i' } }).limit(10); | |
| if (results.length === 0) return ctx.reply('π Bunday tovar topilmadi.', getMainMenu()); | |
| await ctx.reply(`π *Natijalar:* (${results.length} ta)`, { parse_mode: 'Markdown' }); | |
| for(let p of results) { | |
| const msg = `π· *${p.name}*\nπ° Narx: *${formatPrice(p.price)} sum*`; | |
| const buttons = [ | |
| [Markup.button.callback('βοΈ Nomi', `edit_pname_${p._id}`), Markup.button.callback('βοΈ Narx', `edit_price_${p._id}`)], | |
| [Markup.button.callback('π Tavsif', `edit_desc_${p._id}`), Markup.button.callback('πΈ Rasm', `edit_pimg_${p._id}`)], | |
| [Markup.button.callback('π Razmer', `edit_psize_${p._id}`), Markup.button.callback('π O\'chirish', `del_confirm_${p._id}`)] | |
| ]; | |
| if (p.imageUrl && p.imageUrl.startsWith('http')) { | |
| try { | |
| let photoSource = p.imageUrl; | |
| if (photoSource.includes('/api/image/')) photoSource = photoSource.split('/api/image/')[1]; | |
| await ctx.replyWithPhoto(photoSource, { caption: msg, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } catch(e) { | |
| await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } else { | |
| await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) }); | |
| } | |
| } | |
| } catch(e) {} | |
| delete appState[userId]; return; | |
| } | |
| // Yangi Tovar wizard | |
| if (state.step === 'name') { | |
| state.name = text; state.step = 'description'; | |
| ctx.reply('π 2-qadam: Tavsifni yozing:'); | |
| } else if (state.step === 'description') { | |
| state.description = text; state.step = 'price'; | |
| ctx.reply('π° 3-qadam: Narxni yozing (son):'); | |
| } else if (state.step === 'price') { | |
| state.price = Number(text) || 0; state.step = 'category'; | |
| const categories = await Category.find(); | |
| if(categories.length === 0) return ctx.reply('Kategoriya yo\'q! Avval yarating.'); | |
| const buttons = []; let row = []; | |
| categories.forEach((c, i) => { | |
| row.push(Markup.button.callback(c.name, `set_add_cat_${c.name}`)); | |
| if(row.length === 2 || i === categories.length-1) { buttons.push(row); row = []; } | |
| }); | |
| ctx.reply('π 4-qadam: Kategoriyani tanlang:', Markup.inlineKeyboard(buttons)); | |
| } else if (state.step === 'sizes') { | |
| state.sizes = []; | |
| if (text.toLowerCase() !== 'yoq') { | |
| state.sizes = text.split(',').map(s => s.trim()).filter(s => s.length > 0); | |
| } | |
| state.step = 'image'; | |
| ctx.reply('πΌ 6-qadam: Rasm URL yozing yoki rasmni yuboring ("yoq" xam mumkin):'); | |
| } else if (state.step === 'image') { | |
| state.imageUrl = text === 'yoq' ? '' : text; | |
| try { | |
| await new Product(state).save(); | |
| ctx.reply('β Tovar saqlandi!', getMainMenu()); | |
| } catch(e) {} | |
| delete appState[userId]; | |
| return; | |
| } | |
| // --- PUSH XABARNOMA --- | |
| if (state.step === 'push_title') { | |
| appState[userId] = { step: 'push_message', pushTitle: text }; | |
| ctx.reply('π 2-qadam: Xabar matnini yozing:'); | |
| return; | |
| } | |
| if (state.step === 'push_message') { | |
| appState[userId] = { step: 'push_image', pushTitle: state.pushTitle, pushMessage: text }; | |
| ctx.reply('πΌ 3-qadam: Ilovada chiqadigan rasm URL tasvirini yozing (yoki menga hozir rasm yuboring).\n\nAgar rasm kerakmas bo\'lsa "yoq" deb yozing:', { reply_markup: { force_reply: true } }); | |
| return; | |
| } | |
| if (state.step === 'push_image') { | |
| const pushImage = text.toLowerCase() === 'yoq' ? '' : text; | |
| state.pushImage = pushImage; | |
| appState[userId] = { ...state, step: 'push_confirm' }; | |
| ctx.reply(`π’ Siz quyidagi xabarni BARCHA mijoz telefonlariga (Push) yubormoqchisiz:\n\n*Sarlavha:* ${state.pushTitle}\n*Matn:* ${state.pushMessage}\n*Rasm:* ${pushImage ? 'Ulangan' : 'Yo\'q'}\n\nβ Xabarni tasdiqlaysizmi? (ha / yo'q)`, { parse_mode: 'Markdown' }); | |
| return; | |
| } | |
| if (state.step === 'push_confirm') { | |
| if (text.toLowerCase() === 'ha') { | |
| ctx.reply('β³ Xabar yuborilmoqda...'); | |
| const { sendPushToAll } = require('./firebase'); | |
| sendPushToAll(state.pushTitle, state.pushMessage, state.pushImage).then(res => { | |
| if (res.success) { | |
| ctx.reply('β Xabar muvaffaqiyatli HAMMAGA tarqatildi!', getMainMenu()); | |
| } else { | |
| ctx.reply('β Xatolik yuz berdi: ' + res.error, getMainMenu()); | |
| } | |
| }); | |
| } else { | |
| ctx.reply('β Bekor qilindi.', getMainMenu()); | |
| } | |
| delete appState[userId]; | |
| return; | |
| } | |
| }); | |
| bot.action(/set_add_cat_(.+)/, async (ctx) => { | |
| const state = appState[ctx.from.id]; | |
| if(!state || state.step !== 'category') return; | |
| state.category = ctx.match[1]; | |
| state.step = 'sizes'; | |
| ctx.reply('π 5-qadam: Bu tovar qanday razmerlarda bor? Vergul bilan yozing (Masalan: 44, 46, 48).\nYoki razmersiz bo\'lsa "yoq" deb yozing:'); | |
| }); | |
| bot.on('photo', async (ctx) => { | |
| const userId = ctx.from.id; | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[userId]; | |
| if (!state) return; | |
| const photo = ctx.message.photo[ctx.message.photo.length - 1]; | |
| const fileId = photo.file_id; | |
| // Rasmning haqiqiy ID sini olib dinamik url qaytarish, chunki Telegram url 1 soatda eskiredi | |
| const imgUrl = `https://ibrohm-savdobotadmin.hf.space/api/image/${fileId}`; | |
| if (state.step === 'image') { | |
| state.imageUrl = imgUrl; | |
| await new Product(state).save(); | |
| ctx.reply('β Tovar saqlandi!', getMainMenu()); | |
| delete appState[userId]; | |
| } else if(state.step === 'edit_pimg') { | |
| await Product.findByIdAndUpdate(state.pId, { imageUrl: imgUrl }); | |
| ctx.reply('β Rasm yangilandi!', getMainMenu()); | |
| delete appState[userId]; | |
| } else if(state.step === 'banner_wizard_photo') { | |
| // Banner wizard Step 1 β go to step 2, ask for title | |
| appState[userId] = { ...state, step: 'banner_wizard_title', bannerImageUrl: imgUrl }; | |
| ctx.reply(`πΈ *YANGI BANNER* (2/4)\n${thinLine}\n\nπ Banner uchun sarlavha yozing:\n\n_Masalan: "Yozgi Chegirma 50%"_\n\nO'tkazish uchun "yoq" deb yozing.`, { parse_mode: 'Markdown' }); | |
| } else if(state.step === 'push_image') { | |
| state.pushImage = imgUrl; | |
| appState[userId] = { ...state, step: 'push_confirm' }; | |
| ctx.reply(`π’ Siz quyidagi xabarni BARCHA mijoz telefonlariga (Push) yubormoqchisiz:\n\n*Sarlavha:* ${state.pushTitle}\n*Matn:* ${state.pushMessage}\n*Rasm:* Ulangan\n\nβ Xabarni tasdiqlaysizmi? (ha / yo'q)`, { parse_mode: 'Markdown' }); | |
| } | |
| }); | |
| bot.action('action_send_push', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'push_title' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π’ *Xabarnoma yuborish (Push)*\n\n1-qadam: Xabar sarlavhasini yozing (Masalan: π¨ YANGI CHEGIRMA!):', { parse_mode: 'Markdown', reply_markup: { force_reply: true } }); | |
| }); | |
| bot.action('action_set_location', (ctx) => { | |
| if (!isAdmin(ctx)) return; | |
| appState[ctx.from.id] = { step: 'set_store_location' }; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π *Do\'kon Manzilini o\'rnatish*\n\nTelegramning **π Qistirish (Attachment)** tugmasini bosib, xaritadan **Location (Joylashuv)** yuboring.', { parse_mode: 'Markdown' }); | |
| }); | |
| bot.on('location', async (ctx) => { | |
| const userId = ctx.from.id; | |
| if (!isAdmin(ctx)) return; | |
| const state = appState[userId]; | |
| if (!state || state.step !== 'set_store_location') return; | |
| const { latitude, longitude } = ctx.message.location; | |
| try { | |
| const Setting = require('../models/Setting'); | |
| await Setting.findOneAndUpdate( | |
| { key: 'store_location' }, | |
| { value: { lat: latitude, lng: longitude } }, | |
| { upsert: true } | |
| ); | |
| ctx.reply(`β Do'kon manzili muvaffaqiyatli saqlandi!\nπ Koordinatalar: ${latitude}, ${longitude}\n\nIlovadan xaridorlar ushbu xaritani endi bemalol navigator orqali ochishlari mumkin!`, getMainMenu()); | |
| } catch (e) { | |
| ctx.reply('β Saqlashda xatolik yuz berdi: ' + e.message, getMainMenu()); | |
| } | |
| delete appState[userId]; | |
| }); | |
| // Banner wizard β Havola tanlash callbacklari | |
| bot.action('bwiz_link_none', async (ctx) => { | |
| const state = appState[ctx.from.id]; | |
| if (!state) return; | |
| try { | |
| const bannerCount = await Banner.countDocuments({ isActive: true }); | |
| await new Banner({ | |
| imageUrl: state.bannerImageUrl, | |
| title: state.bannerTitle && state.bannerTitle.toLowerCase() !== 'yoq' ? state.bannerTitle : '', | |
| linkType: 'none', | |
| linkValue: '', | |
| order: bannerCount, | |
| isActive: true | |
| }).save(); | |
| ctx.answerCbQuery('β Saqlandi!'); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| ctx.reply('β Yangi banner saqlandi va ilovada ko\'rinadi!', getMainMenu()); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| delete appState[ctx.from.id]; | |
| }); | |
| bot.action(/bwiz_link_cat_(.+)/, async (ctx) => { | |
| const state = appState[ctx.from.id]; | |
| if (!state) return; | |
| try { | |
| const bannerCount = await Banner.countDocuments({ isActive: true }); | |
| await new Banner({ | |
| imageUrl: state.bannerImageUrl, | |
| title: state.bannerTitle && state.bannerTitle.toLowerCase() !== 'yoq' ? state.bannerTitle : '', | |
| linkType: 'category', | |
| linkValue: ctx.match[1], | |
| order: bannerCount, | |
| isActive: true | |
| }).save(); | |
| ctx.answerCbQuery('β Saqlandi!'); | |
| try { ctx.deleteMessage(); } catch(e) {} | |
| ctx.reply(`β Banner saqlandi! Havola: π ${ctx.match[1]}`, getMainMenu()); | |
| } catch(e) { ctx.answerCbQuery('Xato'); } | |
| delete appState[ctx.from.id]; | |
| }); | |
| bot.action('bwiz_link_url', (ctx) => { | |
| const state = appState[ctx.from.id]; | |
| if (!state) return; | |
| state.step = 'banner_wizard_url'; | |
| ctx.answerCbQuery(); | |
| ctx.reply('π Tashqi URL manzilini yozing:', { parse_mode: 'Markdown' }); | |
| }); | |
| bot.launch().then(() => { | |
| console.log('π€ Telegram Bot V4.0 Premium ishga tushdi.'); | |
| }).catch((err) => { | |
| console.error('β Bot ishga tushmadi:', err.message); | |
| }); | |
| } | |
| // ββ Buyurtma holat tugmalari (notifyAdmin uchun) ββββββββββββ | |
| const orderStatusButtonsForNotify = (orderId, currentStatus) => { | |
| const s = (label, status) => currentStatus === status ? `β ${label}` : label; | |
| return Markup.inlineKeyboard([ | |
| [ | |
| Markup.button.callback(s('π₯ Yig\'ish', 'Yig\'ilmoqda'), `order_status_accept_${orderId}`), | |
| Markup.button.callback(s('π Tayyor', 'Olib ketishga tayyor'), `order_status_ship_${orderId}`) | |
| ], | |
| [ | |
| Markup.button.callback(s('β Topshirildi', 'Xaridorga topshirildi'), `order_status_deliver_${orderId}`), | |
| Markup.button.callback(s('β Bekor', 'Bekor qilindi'), `order_status_cancel_${orderId}`) | |
| ] | |
| ]); | |
| }; | |
| // ββ Admin Notification (Yangi buyurtma xabari) ββββββββββββββ | |
| const notifyAdmin = async (orderInfo, orderId) => { | |
| try { | |
| if (bot && process.env.ADMIN_ID) { | |
| const msg = await bot.telegram.sendMessage( | |
| process.env.ADMIN_ID, | |
| orderInfo, | |
| { parse_mode: 'Markdown' } | |
| ); | |
| if (orderId) { | |
| await bot.telegram.editMessageReplyMarkup( | |
| process.env.ADMIN_ID, | |
| msg.message_id, | |
| null, | |
| orderStatusButtonsForNotify(orderId, 'Kutilmoqda').reply_markup | |
| ); | |
| } | |
| } | |
| } catch (e) { | |
| console.error('Adminga xabar yuborishda xato:', e.message); | |
| } | |
| }; | |
| module.exports = { bot, notifyAdmin }; | |