Spaces:
Runtime error
Runtime error
Download server.ts from lasource87/bot: direct link, hf CLI and curl.
- Browser
- Download file 128 kB
-
https://huggingface.co/spaces/lasource87/bot/resolve/main/server.ts
- Command line
-
hf download hf://spaces/lasource87/bot/server.ts
-
curl -L -o server.ts https://huggingface.co/spaces/lasource87/bot/resolve/main/server.ts
128 kB
import express from 'express';
import { createServer as createViteServer } from 'vite';
import { Telegraf, Context, Scenes, session, Markup } from 'telegraf';
import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { HttpsProxyAgent } from 'https-proxy-agent';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const supabaseUrl = process.env.SUPABASE_URL || '';
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY || '';
if (!supabaseUrl || !supabaseServiceKey) {
console.error('CRITICAL: Supabase configuration is missing! Check SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY/SUPABASE_ANON_KEY');
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
const botToken = process.env.TELEGRAM_BOT_TOKEN || '';
const adminId = (process.env.ADMIN_TELEGRAM_ID || '').replace('@', '').trim();
// Helper to format chat ID for Telegram (adds @ to usernames)
const formatChatId = (id: string) => {
if (!id) return null;
const trimmed = id.trim();
if (!trimmed) return null;
// If it's a numeric ID (can be negative for groups)
if (/^-?\d+$/.test(trimmed)) return trimmed;
// If it's a username, ensure it starts with @
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
};
// Helper to check if a user is admin or manager
const isUserAdminOrManager = (userId: string | number, username: string | null, settings: any) => {
const uid = userId.toString().trim();
const uname = (username || '').replace('@', '').trim();
const cleanAdminId = adminId.replace('@', '').trim();
const cleanManagerId = (settings?.manager_chat_id || '').toString().replace('@', '').trim();
const isAdmin = (cleanAdminId && (uid === cleanAdminId || (uname && uname === cleanAdminId)));
const isManager = (cleanManagerId && (uid === cleanManagerId || (uname && uname === cleanManagerId)));
return { isAdmin, isManager, isEither: isAdmin || isManager };
};
// Use a custom URL if provided, otherwise fallback to SHARED_APP_URL or APP_URL
const appUrl = process.env.CUSTOM_APP_URL || process.env.SHARED_APP_URL || process.env.APP_URL || '';
console.log('Config Check:', {
hasBotToken: !!botToken,
adminId: adminId,
hasSupabaseUrl: !!supabaseUrl,
hasSupabaseKey: !!supabaseServiceKey,
isServiceKey: !!process.env.SUPABASE_SERVICE_ROLE_KEY,
appUrl: appUrl
}); // <--- C'est cette parenthèse qui manquait !
// --- MODIFICATION HUGGING FACE ---
const bot = new Telegraf(botToken);
let botUsername = 'Bot';
bot.telegram.getMe().then(me => {
botUsername = me.username;
console.log(`✅ Bot en ligne : @${botUsername}`);
}).catch(err => {
console.log('⚠️ Note: Connexion initiale Telegram impossible, attente du Webhook...');
});
// Set bot descriptions (visible before clicking Start)
const setBotDescriptions = async () => {
try {
const { data: settings } = await supabase.from('shop_settings').select('name, welcome_message').eq('id', 1).single();
const shopName = settings?.name || 'Shop';
// Use the custom welcome message if it exists, otherwise use a dynamic default
let description = settings?.welcome_message || `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\nClique sur COMMANDER pour voir le menu, et n'oublie pas d'aller faire un tour dans la partie info pour tout savoir avant de passer ta commande 😉 ✅`;
// Dynamic replacement of old names if they exist in the saved message
description = description.replace(/Luigi Shop|Ma Boutique/g, shopName);
const shortDescription = `Bot officiel ${shopName} 🇫🇷 - Commandez vos produits préférés en quelques clics !`;
await bot.telegram.setMyDescription(description);
await bot.telegram.setMyShortDescription(shortDescription);
// Set the global menu button to open the web app
if (appUrl) {
await bot.telegram.setChatMenuButton({
menuButton: {
type: 'web_app',
text: 'COMMANDER',
web_app: { url: appUrl }
}
});
}
console.log(`Bot descriptions for "${shopName}" and menu button updated successfully`);
} catch (error) {
console.log('Failed to set bot descriptions:', error.message);
}
};
// Real-time subscription to shop_settings to update bot descriptions
supabase
.channel('shop-settings-changes')
.on('postgres_changes', { event: 'UPDATE', table: 'shop_settings', schema: 'public', filter: 'id=eq.1' }, () => {
console.log('Shop settings updated, refreshing bot descriptions...');
setBotDescriptions();
})
.subscribe();
setBotDescriptions();
const escapeHTML = (str: string) => {
return str.replace(/[&<>"']/g, (m) => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[m as keyof any] || m));
};
function parseAddress(address: string) {
if (!address) return { display: "N/A", query: "N/A" };
const parts = address.split('|');
const display = parts[0];
const query = parts[1] || parts[0]; // Use coords if available, else use display name
return { display, query };
}
async function constructOrderMessage(orderId: string, isManager: boolean, statusSuffix: string = "") {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return "Commande introuvable.";
const { data: userData } = await supabase.from('bot_users').select('phone, username').eq('telegram_id', order.client_telegram_id).single();
const displayUsername = userData?.username ? `@${userData.username}` : (userData?.phone ? `📞 ${userData.phone}` : '<i>Aucun contact</i>');
const orderTypeLabel = order.type === 'meetup' ? '🤝 MEET-UP' : '🚀 LIVRAISON';
const items = order.items || [];
// Style matching the user's image:
// 🔹 ProductName
// └ Format × Count → TotalPrice€
const itemsList = items.map((item: any) =>
`🔹 <b>${escapeHTML(item.productName)}</b>\n` +
` └ ${escapeHTML(item.quantityLabel)} × ${item.count} → <b>${item.price * item.count}€</b>`
).join('\n');
const clientInfo = isManager
? `👤 <b>${escapeHTML(order.client_name || 'Inconnu')}</b> (${displayUsername})`
: `👤 <b>${escapeHTML(order.client_name || 'Inconnu')}</b>`;
let message = `✨ <b>COMMANDE (${orderTypeLabel})</b> ✨\n` +
`${clientInfo}\n` +
`📅 <b>Date:</b> ${new Date(order.created_at).toLocaleString('fr-FR')}\n\n` +
`📦 <b>DÉTAILS DU PANIER :</b>\n` +
itemsList +
`\n\n💰 <b>TOTAL: ${order.total}€</b>\n` +
`📍 <b>${order.type === 'meetup' ? 'RDV' : 'Dest'}:</b> <code>${order.type === 'meetup' && (!order.address || order.address === 'MEETUP') ? 'Donné par le bosseur' : escapeHTML(parseAddress(order.address).display)}</code>`;
if (!statusSuffix) {
if (order.status === 'validated' && order.driver_id) {
const { data: driver } = await supabase.from(order.type === 'meetup' ? 'meetup_workers' : 'drivers').select('first_name').eq('telegram_id', order.driver_id).single();
if (driver) {
message += `\n\n${order.type === 'meetup' ? '🤝' : '📦'} <b>PRIS EN CHARGE PAR :</b> ${escapeHTML(driver.first_name)}`;
}
} else if (order.status === 'completed' && order.completed_by_name) {
message += `\n\n🏁 <b>${order.type === 'meetup' ? 'MEETUP' : 'LIVRAISON'} TERMINÉ & ENCAISSÉ PAR :</b> ${escapeHTML(order.completed_by_name)}`;
}
}
return `${message}${statusSuffix}`;
}
async function generateDriverRecap(driverId: string) {
const { data: orders } = await supabase.from('orders')
.select('*')
.eq('driver_id', driverId)
.eq('status', 'validated')
.order('created_at', { ascending: true });
if (!orders || orders.length === 0) {
return { text: "📭 Vous n'avez aucune commande en cours.", keyboard: [] };
}
let text = `📋 <b>RÉCAPITULATIF DES COMMANDES (${orders.length})</b>\n`;
text += `━━━━━━━━━━━━━━━━━━━━\n\n`;
const buttons: any[][] = [];
const destinations: string[] = [];
orders.forEach((order, index) => {
const items = order.items || [];
const itemsSummary = items.map((i: any) => `${i.productName} (${i.quantityLabel}) x${i.count} → ${i.price * i.count}€`).join(', ');
const { display, query } = parseAddress(order.address);
text += `📍 <b>${index + 1}. ${escapeHTML(display)}</b>\n`;
text += `👤 ${escapeHTML(order.client_name || 'Inconnu')} | 📦 ${escapeHTML(itemsSummary)}\n`;
text += `┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈\n`;
if (order.type !== 'meetup') {
destinations.push(query);
}
// Button for each order
const clientName = (order.client_name || 'Inconnu').toString();
const summary = (itemsSummary || 'Sans détails').toString();
// Safely truncate to 20 characters (respecting emojis)
const truncatedSummary = Array.from(summary).slice(0, 20).join('');
const buttonText = `🔍 ${clientName} - ${truncatedSummary}${Array.from(summary).length > 20 ? '...' : ''}`;
buttons.push([{
text: buttonText,
callback_data: `view_order_full_${order.id}`
}]);
});
if (destinations.length > 0) {
// Google Maps Multi-stop
const waypoints = destinations.slice(0, -1).map(d => encodeURIComponent(d)).join('|');
const destination = encodeURIComponent(destinations[destinations.length - 1]);
const googleUrl = `https://www.google.com/maps/dir/?api=1&destination=${destination}${waypoints ? `&waypoints=${waypoints}` : ''}&travelmode=driving`;
// Apple Maps Multi-stop
const appleUrl = `http://maps.apple.com/?daddr=${destinations.map(d => encodeURIComponent(d)).join('+to:')}`;
// Waze (only first destination)
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(destinations[0])}`;
buttons.unshift([
{ text: "🗺️ GOOGLE", url: googleUrl },
{ text: "🍎 APPLE", url: appleUrl },
{ text: "🚙 WAZE", url: wazeUrl }
]);
buttons.unshift([{ text: "📍 OPTIMISER MON TRAJET", callback_data: "driver_optimize_info" }]);
}
buttons.push([{ text: "🔄 ACTUALISER LE RÉCAPITULATIF", callback_data: "driver_refresh_recap" }]);
return { text, keyboard: buttons };
}
// Helper to handle "message is not modified" error
const safeEdit = async (fn: () => Promise<any>) => {
try {
return await fn();
} catch (err: any) {
if (err.description?.includes('message is not modified')) {
return;
}
throw err;
}
};
// Middleware de log et tracking
bot.use(async (ctx, next) => {
if (ctx.from) {
try {
await supabase.from('bot_users').upsert({
telegram_id: ctx.from.id.toString(),
username: ctx.from.username,
first_name: ctx.from.first_name,
last_seen: new Date().toISOString()
}, { onConflict: 'telegram_id' });
} catch (e) {
// Silently fail if table missing or error
}
}
// Track group/channel integration
if (ctx.chat && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup' || ctx.chat.type === 'channel')) {
try {
await supabase.from('integrated_chats').upsert({
chat_id: ctx.chat.id.toString(),
chat_title: 'title' in ctx.chat ? ctx.chat.title : 'Chat',
chat_type: ctx.chat.type,
added_at: new Date().toISOString()
}, { onConflict: 'chat_id' });
} catch (e) {}
}
const messageText = ctx.message && 'text' in ctx.message ? ctx.message.text : 'non-texte/callback';
console.log(`Update reçu de ${ctx.from?.id} [${ctx.updateType}]: ${messageText}`);
return next();
});
bot.on('my_chat_member', async (ctx) => {
const chat = ctx.myChatMember.chat;
const status = ctx.myChatMember.new_chat_member.status;
try {
if (status === 'member' || status === 'administrator') {
await supabase.from('integrated_chats').upsert({
chat_id: chat.id.toString(),
chat_title: 'title' in chat ? chat.title : 'Chat',
chat_type: chat.type,
added_at: new Date().toISOString()
}, { onConflict: 'chat_id' });
} else if (status === 'left' || status === 'kicked') {
await supabase.from('integrated_chats').delete().eq('chat_id', chat.id.toString());
}
} catch (e) {
console.error('Error tracking integrated chat:', e);
}
});
bot.on('contact', async (ctx) => {
if (ctx.message.contact) {
const phone = ctx.message.contact.phone_number;
const telegramId = ctx.from.id.toString();
await supabase.from('bot_users').update({ phone }).eq('telegram_id', telegramId);
ctx.reply("✅ Votre numéro de téléphone a été enregistré. Vous pouvez maintenant passer commande !", {
reply_markup: { remove_keyboard: true }
});
}
});
// --- Bot Logic ---
bot.start(async (ctx) => {
try {
const payload = ctx.startPayload;
// Track user
const telegramId = ctx.from.id.toString();
const username = ctx.from.username || null;
const firstName = ctx.from.first_name || 'Inconnu';
await supabase.from('bot_users').upsert({
telegram_id: telegramId,
username: username,
first_name: firstName,
last_seen: new Date().toISOString()
}, { onConflict: 'telegram_id' });
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
// If payload is 'info', we show info directly
if (payload === 'info') {
const shopName = settings?.name || 'Shop';
const logoUrl = settings?.logo_url || '';
let infoText = settings?.info_text || `ℹ️ INFORMATIONS\n\nBienvenue chez ${shopName} ! 🇫🇷\n\n🚀 Livraison rapide et sécurisée\n💎 Produits de qualité supérieure\n💬 Support client réactif\n\nPour toute question, n'hésitez pas à nous contacter via le bouton 'Nous Contacter'.`;
// Dynamic replacement of old names if they exist in the saved message
infoText = infoText.replace(/Luigi Shop|Ma Boutique/g, shopName);
const infoKeyboard = {
inline_keyboard: [
[{ text: "🟢 COMMANDER 🟢", web_app: { url: appUrl } }],
[{ text: "Retour", callback_data: "bot_start_back" }]
]
};
if (logoUrl) {
return ctx.replyWithPhoto(logoUrl, {
caption: infoText,
reply_markup: infoKeyboard
});
}
return ctx.reply(infoText, {
reply_markup: infoKeyboard
});
}
const shopName = settings?.name || 'Shop';
const logoUrl = settings?.logo_url || '';
const manager = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const isOpen = settings?.is_open !== false; // Default to true if column missing or null
const { data: userData } = await supabase.from('bot_users').select('phone, verification_status').eq('telegram_id', ctx.from.id.toString()).single();
const hasPhone = !!userData?.phone;
const isVerified = userData?.verification_status === 'approved';
const { isAdmin, isManager, isEither } = isUserAdminOrManager(ctx.from.id, ctx.from.username || null, settings);
// Verification check
if (settings?.is_verification_enabled && !isVerified && !isEither) {
// Check if already pending
if (userData?.verification_status === 'pending') {
return ctx.reply("⏳ <b>VOTRE COMPTE EST EN COURS DE VÉRIFICATION</b>\n\nUn manager examine actuellement votre demande. Vous recevrez une notification dès que votre accès sera validé.\n\nMerci de votre patience ! 🙏", {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ ÉCRIRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
}
// Start verification process
userState[ctx.from.id] = { step: 'awaiting_referral_info', data: {} };
return ctx.reply("🛡️ <b>SYSTÈME DE VÉRIFICATION</b>\n\nBienvenue ! Pour accéder au shop, nous devons vérifier votre identité.\n\n👉 Veuillez envoyer le <b>@username</b> ou le <b>numéro de téléphone</b> de la personne qui vous a recommandé (votre parrain).\n\n<i>Cette étape est obligatoire pour garantir la sécurité de notre communauté.</i>", {
parse_mode: 'HTML'
});
}
let welcomeMsg = isOpen
? (settings?.welcome_message || `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\nClique sur COMMANDER pour voir le menu, et n'oublie pas d'aller faire un tour dans la partie info pour tout savoir avant de passer ta commande 😉 ✅`)
: `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\n🔴 LE SHOP EST ACTUELLEMENT FERMÉ 🔴\n\nRevenez plus tard pour passer commande. Vous serez notifié dès la réouverture !`;
// Dynamic replacement of old names if they exist in the saved message
welcomeMsg = welcomeMsg.replace(/Luigi Shop|Ma Boutique/g, shopName);
const keyboard: any = {
inline_keyboard: []
};
if (isOpen || isEither) {
keyboard.inline_keyboard.push([{ text: "🟢 COMMANDER 🟢", web_app: { url: appUrl } }]);
}
if (isEither) {
keyboard.inline_keyboard.push([{ text: "⚙️ RÉGLAGES ADMIN ⚙️", web_app: { url: `${appUrl}/settings` } }]);
}
keyboard.inline_keyboard.push([
{ text: "Informations ℹ️", callback_data: "bot_info" },
{ text: "Nous Contacter...", url: `https://t.me/${manager}` }
]);
keyboard.inline_keyboard.push([{ text: "Notre Canal ↗️", url: settings?.channel_url || "https://t.me/hftfrance" }]);
if (isOpen || isEither) {
if (!ctx.from.username && !hasPhone) {
// Send a separate message with the reply keyboard to ask for the phone number
await ctx.reply("⚠️ Pour commander sans pseudonyme Telegram (@), nous avons besoin de votre numéro de téléphone pour que nous puissions vous contacter concernant votre commande.", {
reply_markup: {
keyboard: [[{ text: "📱 Partager mon numéro pour commander", request_contact: true }]],
resize_keyboard: true,
one_time_keyboard: true
}
});
}
// Set the menu button to open the web app
try {
await ctx.setChatMenuButton({
type: 'web_app',
text: isEither ? 'ADMIN' : 'COMMANDER',
web_app: { url: isEither ? `${appUrl}/settings` : appUrl }
});
} catch (e) {
console.error('Failed to set chat menu button:', e);
}
} else {
// Remove menu button if closed, UNLESS it's an admin/manager
if (isEither) {
try {
await ctx.setChatMenuButton({
type: 'web_app',
text: 'ADMIN',
web_app: { url: `${appUrl}/settings` }
});
} catch (e) {}
} else {
try {
await ctx.setChatMenuButton({ type: 'default' });
} catch (e) {}
}
}
if (logoUrl) {
await ctx.replyWithPhoto(logoUrl, {
caption: welcomeMsg,
reply_markup: keyboard
});
} else {
await ctx.reply(welcomeMsg, {
reply_markup: keyboard
});
}
} catch (err) {
console.error('Error in start command:', err);
ctx.reply(`Bienvenue chez votre Shop ! 🛍️\n\nCliquez sur le bouton ci-dessous pour commander.`, {
reply_markup: {
inline_keyboard: [
[{ text: "🟢 COMMANDER 🟢", web_app: { url: appUrl } }]
]
}
});
}
});
bot.action('bot_info', async (ctx) => {
try {
await ctx.deleteMessage();
} catch (e) {}
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither: isEither } = isUserAdminOrManager(ctx.from.id, ctx.from.username || null, settings);
const isOpen = settings?.is_open !== false;
const shopName = settings?.name || 'Shop';
const logoUrl = settings?.logo_url || '';
let infoText = settings?.info_text || `ℹ️ INFORMATIONS\n\nBienvenue chez ${shopName} ! 🇫🇷\n\n🚀 Livraison rapide et sécurisée\n💎 Produits de qualité supérieure\n💬 Support client réactif\n\nPour toute question, n'hésitez pas à nous contacter via le bouton 'Nous Contacter'.`;
// Dynamic replacement of old names if they exist in the saved message
infoText = infoText.replace(/Luigi Shop|Ma Boutique/g, shopName);
const keyboard = {
inline_keyboard: [] as any[][]
};
if (isOpen || isEither) {
keyboard.inline_keyboard.push([{ text: "🟢 COMMANDER 🟢", web_app: { url: appUrl } }]);
}
if (isEither) {
keyboard.inline_keyboard.push([{ text: "⚙️ RÉGLAGES ADMIN ⚙️", web_app: { url: `${appUrl}/settings` } }]);
}
keyboard.inline_keyboard.push([{ text: "Retour", callback_data: "bot_start_back" }]);
if (logoUrl) {
await ctx.replyWithPhoto(logoUrl, {
caption: infoText,
reply_markup: keyboard
});
} else {
await ctx.reply(infoText, {
reply_markup: keyboard
});
}
});
bot.action('bot_start_back', async (ctx) => {
try {
await ctx.deleteMessage();
} catch (e) {}
// Re-trigger start logic or just send the start message again
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither: isEither } = isUserAdminOrManager(ctx.from.id, ctx.from.username || null, settings);
const isOpen = settings?.is_open !== false;
const shopName = settings?.name || 'Shop';
const logoUrl = settings?.logo_url || '';
const manager = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const welcomeMsg = isOpen
? (settings?.welcome_message || `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\nClique sur COMMANDER pour voir le menu, et n'oublie pas d'aller faire un tour dans la partie info pour tout savoir avant de passer ta commande 😉 ✅`)
: `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\n🔴 LE SHOP EST ACTUELLEMENT FERMÉ 🔴\n\nRevenez plus tard pour passer commande. Vous serez notifié dès la réouverture !`;
const keyboard = {
inline_keyboard: [] as any[][]
};
if (isOpen || isEither) {
keyboard.inline_keyboard.push([{ text: "🟢 COMMANDER 🟢", web_app: { url: appUrl } }]);
}
if (isEither) {
keyboard.inline_keyboard.push([{ text: "⚙️ RÉGLAGES ADMIN ⚙️", web_app: { url: `${appUrl}/settings` } }]);
}
keyboard.inline_keyboard.push([
{ text: "Informations ℹ️", callback_data: "bot_info" },
{ text: "Nous Contacter...", url: `https://t.me/${manager}` }
]);
keyboard.inline_keyboard.push([{ text: "Notre Canal ↗️", url: settings?.channel_url || "https://t.me/hftfrance" }]);
if (logoUrl) {
await ctx.replyWithPhoto(logoUrl, {
caption: welcomeMsg,
reply_markup: keyboard
});
} else {
await ctx.reply(welcomeMsg, {
reply_markup: keyboard
});
}
});
bot.command('groupe', async (ctx) => {
const chatId = ctx.chat.id;
const chatType = ctx.chat.type;
const chatTitle = (ctx.chat as any).title || 'Privé';
await ctx.reply(`🆔 ID de ce chat : <code>${chatId}</code>\n📂 Type : <b>${chatType}</b>\n🏷 Titre : <b>${chatTitle}</b>`, { parse_mode: 'HTML' });
});
bot.command('post', async (ctx) => {
const userId = ctx.from.id.toString();
const { data: settings } = await supabase.from('shop_settings').select('manager_chat_id, order_manager, name, logo_url, channel_url, welcome_message').eq('id', 1).single();
const { isEither: isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
if (!isManager) return;
const shopName = settings?.name || 'Shop';
const defaultLogo = settings?.logo_url || '';
const manager = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const botUsername = ctx.botInfo.username;
const keyboard = {
inline_keyboard: [
[
{ text: "Informations ℹ️", url: `https://t.me/${botUsername}?start=info` },
{ text: "Nous Contacter...", url: `https://t.me/${manager}` }
],
[{ text: "Notre Canal ↗️", url: settings?.channel_url || "https://t.me/hftfrance" }],
[{ text: "🟢 COMMANDER 🟢", url: `https://t.me/${botUsername}?start=order` }]
]
};
// Parse arguments: /post [target] [text...]
const fullText = ctx.message.text || '';
const parts = fullText.split(' ');
let targetId: string | number = ctx.chat.id;
let customText = '';
if (parts[1] && (parts[1].startsWith('@') || /^-?\d+$/.test(parts[1]))) {
targetId = parts[1];
customText = parts.slice(2).join(' ');
} else {
customText = parts.slice(1).join(' ');
}
const finalMsg = customText || settings?.welcome_message || `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\nClique sur COMMANDER pour voir le menu, et n'oublie pas d'aller faire un tour dans la partie info pour tout savoir avant de passer ta commande 😉 ✅`;
try {
if (defaultLogo) {
await ctx.telegram.sendPhoto(targetId, defaultLogo, {
caption: finalMsg,
reply_markup: keyboard,
parse_mode: 'HTML'
});
} else {
await ctx.telegram.sendMessage(targetId, finalMsg, {
reply_markup: keyboard,
parse_mode: 'HTML'
});
}
if (parts[1]) ctx.reply("✅ Message diffusé avec succès !");
} catch (e) {
ctx.reply(`❌ Erreur : ${e.message}. Assurez-vous que le bot est bien administrateur du groupe/canal.`);
}
});
// Handle /post when sent as a photo caption
bot.on('photo', async (ctx, next) => {
const caption = ctx.message.caption || '';
if (!caption.startsWith('/post')) return next();
const userId = ctx.from.id.toString();
const { data: settings } = await supabase.from('shop_settings').select('manager_chat_id, order_manager, name, channel_url').eq('id', 1).single();
const { isEither: isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
if (!isManager) return;
const shopName = settings?.name || 'Shop';
const manager = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const botUsername = ctx.botInfo.username;
const keyboard = {
inline_keyboard: [
[
{ text: "Informations ℹ️", url: `https://t.me/${botUsername}?start=info` },
{ text: "Nous Contacter...", url: `https://t.me/${manager}` }
],
[{ text: "Notre Canal ↗️", url: settings?.channel_url || "https://t.me/hftfrance" }],
[{ text: "🟢 COMMANDER 🟢", url: `https://t.me/${botUsername}?start=order` }]
]
};
const parts = caption.split(' ');
let targetId: string | number = ctx.chat.id;
let customText = '';
if (parts[1] && (parts[1].startsWith('@') || /^-?\d+$/.test(parts[1]))) {
targetId = parts[1];
customText = parts.slice(2).join(' ');
} else {
customText = parts.slice(1).join(' ');
}
const photo = ctx.message.photo[ctx.message.photo.length - 1].file_id;
try {
await ctx.telegram.sendPhoto(targetId, photo, {
caption: customText,
reply_markup: keyboard,
parse_mode: 'HTML'
});
if (parts[1]) ctx.reply("✅ Photo diffusée avec succès !");
} catch (e) {
ctx.reply(`❌ Erreur : ${e.message}`);
}
});
bot.command('recap', async (ctx) => {
const driverId = ctx.from.id.toString();
// Check if user is a driver
const { data: driver } = await supabase.from('drivers').select('*').eq('telegram_id', driverId).single();
const { data: settings } = await supabase.from('shop_settings').select('manager_chat_id').eq('id', 1).single();
const { isEither: isManager } = isUserAdminOrManager(driverId, ctx.from.username || null, settings);
if (!driver && !isManager) {
return ctx.reply("❌ Accès refusé. Cette commande est réservée aux livreurs.");
}
const recap = await generateDriverRecap(driverId);
await ctx.reply(recap.text, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
});
});
bot.command('driver', async (ctx) => {
const driverId = ctx.from.id.toString();
// Check if user is a driver
const { data: driver } = await supabase.from('drivers').select('*').eq('telegram_id', driverId).single();
const { data: settings } = await supabase.from('shop_settings').select('manager_chat_id').eq('id', 1).single();
const { isEither: isManager } = isUserAdminOrManager(driverId, ctx.from.username || null, settings);
if (!driver && !isManager) {
return ctx.reply("❌ Accès refusé. Cette commande est réservée aux livreurs.");
}
ctx.reply(`🚀 PANNEAU LIVREUR 🚀\n\nBienvenue ${ctx.from.first_name || 'Livreur'} !\n\nQue souhaitez-vous faire ?`, {
reply_markup: {
inline_keyboard: [
[{ text: "📋 VOIR MES COMMANDES EN COURS", callback_data: "driver_view_recap" }],
[{ text: "📊 VOIR MES COMPTES", callback_data: "driver_view_stats" }]
]
}
});
});
bot.command('clear', async (ctx) => {
await ctx.telegram.setMyCommands([]);
ctx.reply("Commandes du menu Telegram effacées ! ✅");
});
bot.command('seting', async (ctx) => {
const userId = ctx.from.id.toString();
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isAdmin, isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
if (!isAdmin && !isManager) {
return; // Silently ignore if not admin or manager
}
ctx.reply(`🛠️ <b>ACCÈS AUX RÉGLAGES</b> 🛠️\n\nCliquez sur le bouton ci-dessous pour accéder à l'interface graphique des réglages.`, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [[{
text: "⚙️ OUVRIR LES RÉGLAGES ⚙️",
web_app: { url: `${appUrl}/settings` }
}]]
}
});
});
// Simple state management for adding items
const userState: Record<number, { step: string, data: any }> = {};
// Helper to show price manager
async function showPriceManager(ctx: any, productId: string) {
const { data: product } = await supabase.from('products').select('name').eq('id', productId).single();
const { data: prices } = await supabase.from('product_prices').select('*').eq('product_id', productId).order('price');
let msg = `💰 GESTION DES TARIFS\n📦 Produit : ${product?.name || 'Inconnu'}\n\n`;
const buttons = [];
if (prices && prices.length > 0) {
prices.forEach(p => {
msg += `• ${p.quantity} : ${p.price}€\n`;
buttons.push([{ text: `❌ Supprimer ${p.quantity}`, callback_data: `del_price_${p.id}` }]);
});
msg += "\nCliquez sur un bouton pour supprimer un tarif.";
} else {
msg += "Aucun tarif configuré pour ce produit.";
}
buttons.push([{ text: "➕ AJOUTER UN TARIF", callback_data: `add_price_to_${productId}` }]);
buttons.push([{ text: "⬅️ RETOUR AU PRODUIT", callback_data: `edit_prod_${productId}` }]);
ctx.reply(msg, { reply_markup: { inline_keyboard: buttons } });
}
bot.on('callback_query', async (ctx: any) => {
const data = ctx.callbackQuery.data;
const userId = ctx.from.id;
if (data === 'toggle_verification') {
const { data: settings } = await supabase.from('shop_settings').select('manager_chat_id').eq('id', 1).single();
const { isAdmin, isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
if (!isAdmin && !isManager) {
return ctx.answerCbQuery("Accès refusé : vous n'êtes pas admin ou manager.");
}
const { data: currentSettings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const newValue = !currentSettings?.is_verification_enabled;
const { error } = await supabase.from('shop_settings').update({ is_verification_enabled: newValue }).eq('id', 1);
if (error) {
ctx.answerCbQuery(`Erreur : ${error.message}`);
} else {
ctx.answerCbQuery(`✅ Vérification ${newValue ? 'activée' : 'désactivée'} !`);
}
}
else if (data.startsWith('approve_user_')) {
const targetUserId = data.replace('approve_user_', '');
try {
await supabase.from('bot_users').update({ verification_status: 'approved' }).eq('telegram_id', targetUserId);
// Notify client
await bot.telegram.sendMessage(targetUserId, "🎉 <b>VOTRE ACCÈS A ÉTÉ VALIDÉ !</b>\n\nFélicitations, vous pouvez désormais accéder au shop et passer vos commandes.\n\nCliquez sur /start pour commencer ! ✅", {
parse_mode: 'HTML'
});
ctx.answerCbQuery("✅ Utilisateur approuvé !");
ctx.editMessageText(ctx.callbackQuery.message.text + "\n\n✅ <b>APPROUVÉ</b>", { parse_mode: 'HTML' });
} catch (e) {
console.error('Error approving user:', e);
ctx.answerCbQuery("❌ Erreur lors de l'approbation.");
}
}
else if (data.startsWith('reject_user_')) {
const targetUserId = data.replace('reject_user_', '');
try {
await supabase.from('bot_users').update({ verification_status: 'rejected' }).eq('telegram_id', targetUserId);
// Notify client
await bot.telegram.sendMessage(targetUserId, "❌ <b>ACCÈS REFUSÉ</b>\n\nDésolé, votre demande d'accès a été refusée par le manager.\n\nSi vous pensez qu'il s'agit d'une erreur, vous pouvez contacter le support.", {
parse_mode: 'HTML'
});
ctx.answerCbQuery("❌ Utilisateur refusé !");
ctx.editMessageText(ctx.callbackQuery.message.text + "\n\n❌ <b>REFUSÉ</b>", { parse_mode: 'HTML' });
} catch (e) {
console.error('Error rejecting user:', e);
ctx.answerCbQuery("❌ Erreur lors du refus.");
}
}
else if (data === 'contact_manager_verification') {
userState[userId] = { step: 'awaiting_verification_msg_to_manager', data: {} };
ctx.reply("✍️ <b>ÉCRIRE AU MANAGER</b>\n\nVeuillez envoyer votre message ci-dessous. Il sera transmis directement au manager chargé des vérifications.", {
parse_mode: 'HTML'
});
ctx.answerCbQuery();
}
else if (data.startsWith('msg_client_v_')) {
const targetUserId = data.replace('msg_client_v_', '');
userState[userId] = { step: 'awaiting_verification_msg_to_client', data: { targetUserId } };
ctx.reply("✍️ <b>RÉPONDRE AU CLIENT</b>\n\nVeuillez envoyer votre message ci-dessous. Il sera transmis directement au client.", {
parse_mode: 'HTML'
});
ctx.answerCbQuery();
}
else if (data.startsWith('take_order_') || data.startsWith('take_meetup_')) {
const isMeetup = data.startsWith('take_meetup_');
const orderId = data.split('_')[2];
const driverId = ctx.from.id.toString();
try {
// Check if order is still pending
const { data: order, error: orderErr } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (orderErr || !order) {
return ctx.answerCbQuery("Erreur : Commande introuvable.");
}
if (order.status !== 'pending') {
if (order.driver_id === driverId) {
// If it's the same driver, we continue to update the message just in case buttons were missed
ctx.answerCbQuery(isMeetup ? "✅ Vous avez déjà pris ce meetup !" : "✅ Vous avez déjà pris cette commande !");
} else {
return ctx.answerCbQuery(isMeetup ? "❌ Désolé, ce meetup a déjà été prise par un autre collaborateur." : "❌ Désolé, cette commande a déjà été prise par un autre livreur.");
}
} else {
// Update order status only if it was pending
const { error: updateErr } = await supabase.from('orders').update({
status: 'validated',
driver_id: driverId
}).eq('id', orderId);
if (updateErr) throw updateErr;
ctx.answerCbQuery(isMeetup ? "✅ Meetup pris en charge !" : "✅ Commande prise en charge !");
}
// Fetch updated order to get all fields
const { data: updatedOrder } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!updatedOrder) throw new Error("Commande introuvable après mise à jour.");
const driverName = ctx.from.first_name || ctx.from.username || (isMeetup ? "Un collaborateur" : "Un livreur");
const statusSuffix = isMeetup
? `\n\n🤝 <b>PRIS EN CHARGE PAR :</b> ${driverName}`
: `\n\n📦 <b>PRISE EN CHARGE PAR :</b> ${driverName}`;
// Update all notifications
const { data: notifications } = await supabase.from('order_notifications').select('*').eq('order_id', orderId);
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const managerUsername = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
if (notifications) {
for (const notif of notifications) {
try {
const currentDriverId = notif.driver_id === 'manager' || notif.driver_id === 'admin' ? notif.driver_id : notif.driver_id;
const isPrivilegedNotif = notif.driver_id === 'manager' || notif.driver_id === 'admin';
const updatedText = await constructOrderMessage(orderId, isPrivilegedNotif, statusSuffix);
const { query } = parseAddress(updatedOrder.address);
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const isMeetup = updatedOrder.type === 'meetup';
const baseButtons = isMeetup ? [] : [
[
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
],
[{ text: "🚙 WAZE", url: wazeUrl }]
];
let keyboard = [];
if (isPrivilegedNotif) {
keyboard = baseButtons;
} else if (currentDriverId === driverId) {
keyboard = [
...baseButtons,
[{ text: "✉️ ÉCRIRE AU CLIENT", callback_data: `msg_client_${updatedOrder.id}` }],
[{ text: "🔔 ARRIVÉE DANS 3 MIN", callback_data: `notify_arrival_${updatedOrder.id}` }],
[{ text: "💰 ENCAISSER LA COMMANDE", callback_data: `c_in_${updatedOrder.id}` }],
[{ text: "❌ ANNULER LA COMMANDE", callback_data: `cancel_order_${updatedOrder.id}` }]
];
} else {
keyboard = []; // Other drivers see no buttons
}
let targetChatId: string | null = null;
if (notif.driver_id === 'admin') {
targetChatId = formatChatId(adminId);
} else if (notif.driver_id === 'manager') {
targetChatId = formatChatId(settings?.manager_chat_id);
} else {
targetChatId = currentDriverId;
}
if (targetChatId) {
await safeEdit(() => bot.telegram.editMessageText(targetChatId!, notif.message_id, undefined, updatedText, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: keyboard }
}));
}
} catch (e) {
console.error('Failed to update notification:', e);
}
}
}
// Notify client if it was just taken (status was pending before our update check)
if (order.status === 'pending' && updatedOrder.client_telegram_id) {
const clientMsg = updatedOrder.type === 'meetup'
? `✅ <b>Votre commande a été validée !</b>\n\nLe collaborateur prépare votre commande et vous contactera très bientôt pour fixer le rendez-vous.`
: `✅ <b>Votre commande a été validée !</b>\n\nLe livreur prépare votre commande et vous contactera très bientôt pour le délai d'attente.`;
const clientButtons = [
[{
text: updatedOrder.type === 'meetup' ? "🤝 CONTACTER LE MEET-UP" : "🛵 CONTACTER LE LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
];
await bot.telegram.sendMessage(updatedOrder.client_telegram_id, clientMsg, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: clientButtons }
});
}
// Send Recap to Driver
const recap = await generateDriverRecap(driverId);
await ctx.reply(recap.text, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
});
} catch (err: any) {
console.error('Error taking order:', err);
ctx.answerCbQuery(`Erreur : ${err.message}`);
}
}
else if (data.startsWith('v_ord_')) {
const orderId = data.split('_')[2];
try {
const { data: order, error: fetchErr } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (fetchErr || !order) {
return ctx.answerCbQuery("Erreur : Commande introuvable.");
}
const clientId = order.client_telegram_id;
const total = order.total;
// Update order status in DB
await supabase.from('orders').update({ status: 'validated' }).eq('id', orderId);
// 1. Notify the client via the bot
const clientMsg = order.type === 'meetup'
? `✅ <b>Votre commande a été validée !</b>\n\nLe collaborateur prépare votre commande et vous contactera très bientôt pour fixer le rendez-vous.`
: `✅ <b>Votre commande a été validée !</b>\n\nLe livreur prépare votre commande et vous contactera très bientôt pour le délai d'attente.`;
if (clientId) {
const clientButtons = [
[{
text: order.type === 'meetup' ? "🤝 CONTACTER LE MEET-UP" : "🛵 CONTACTER LE LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
];
await bot.telegram.sendMessage(clientId, clientMsg, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: clientButtons }
});
}
// 2. Update all notifications (Manager and Driver)
const { data: notifications } = await supabase.from('order_notifications').select('*').eq('order_id', orderId);
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const shopName = settings?.name || 'HFT FRANCE';
const preFilledText = encodeURIComponent(`Bonjour, je suis votre livreur ${shopName}. Votre commande de ${total}€ a été validée ! Je vous contacte pour vous donner le délai d'attente.`);
const chatUrl = `tg://user?id=${clientId}&text=${preFilledText}`;
const { query } = parseAddress(order?.address || '');
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const isMeetup = order.type === 'meetup';
const baseButtons = isMeetup ? [[{ text: "💬 CONTACTER LE CLIENT MAINTENANT", url: chatUrl }]] : [
[
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
],
[{ text: "🚙 WAZE", url: wazeUrl }],
[{ text: "💬 CONTACTER LE CLIENT MAINTENANT", url: chatUrl }]
];
if (notifications) {
for (const notif of notifications) {
try {
const isManagerNotif = notif.driver_id === 'manager';
const statusSuffix = "\n\n✅ <b>COMMANDE VALIDÉE</b>";
const newText = await constructOrderMessage(orderId, isManagerNotif, statusSuffix);
let keyboard = [];
const currentDriverId = notif.driver_id === 'manager' ? 'manager' : notif.driver_id;
if (currentDriverId === 'manager') {
keyboard = baseButtons;
} else if (currentDriverId === order?.driver_id) {
keyboard = [
...baseButtons,
[{ text: "💰 ENCAISSER LA COMMANDE", callback_data: `c_in_${orderId}` }],
[{ text: "❌ ANNULER LA COMMANDE", callback_data: `cancel_order_${orderId}` }]
];
} else {
keyboard = [];
}
const targetChatId = isManagerNotif ? settings?.manager_chat_id || adminId : currentDriverId;
await safeEdit(() => bot.telegram.editMessageText(targetChatId, notif.message_id, undefined, newText, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: keyboard }
}));
} catch (e) {}
}
}
ctx.answerCbQuery("Commande validée ! Client notifié.");
} catch (err) {
console.error('Error in validate_order:', err);
ctx.answerCbQuery("Erreur lors de la validation.");
}
}
else if (data === 'driver_view_recap') {
try {
await ctx.deleteMessage();
} catch (e) {}
const recap = await generateDriverRecap(userId.toString());
await ctx.reply(recap.text, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
});
ctx.answerCbQuery();
}
else if (data === 'driver_view_stats') {
const { data: orders } = await supabase.from('orders').select('*').eq('driver_id', userId.toString()).eq('status', 'completed');
const total = orders?.reduce((acc, o) => acc + (o.total || 0), 0) || 0;
const count = orders?.length || 0;
await ctx.reply(`📊 <b>VOS STATISTIQUES</b>\n\n✅ Commandes livrées : ${count}\n💰 Total encaissé : ${total.toFixed(2)}€`, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [[{ text: "🔙 RETOUR", callback_data: "driver_view_panel" }]]
}
});
ctx.answerCbQuery();
}
else if (data === 'driver_view_panel') {
ctx.editMessageText(`🚀 PANNEAU LIVREUR 🚀\n\nBienvenue ${ctx.from.first_name || 'Livreur'} !\n\nQue souhaitez-vous faire ?`, {
reply_markup: {
inline_keyboard: [
[{ text: "📋 VOIR MES COMMANDES EN COURS", callback_data: "driver_view_recap" }],
[{ text: "📊 VOIR MES COMPTES", callback_data: "driver_view_stats" }]
]
}
});
ctx.answerCbQuery();
}
else if (data === 'driver_refresh_recap') {
const driverId = ctx.from.id.toString();
const recap = await generateDriverRecap(driverId);
await safeEdit(() => ctx.editMessageText(recap.text, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
}));
ctx.answerCbQuery("Récapitulatif actualisé !");
}
else if (data === 'driver_optimize_info') {
ctx.answerCbQuery("🚀 Choisissez votre application pour lancer l'itinéraire optimisé de vos livraisons.");
}
else if (data.startsWith('view_order_full_')) {
const orderId = data.split('_')[3];
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.answerCbQuery("Commande introuvable.");
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither: isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
const driverId = ctx.from.id.toString();
const isAssignedDriver = String(order.driver_id) === driverId;
const msg = await constructOrderMessage(orderId, isManager);
const { query } = parseAddress(order.address);
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const isMeetup = order.type === 'meetup';
const baseButtons = isMeetup ? [] : [
[
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
],
[{ text: "🚙 WAZE", url: wazeUrl }]
];
let keyboard = [];
if (isAssignedDriver || isManager) {
keyboard = [
...baseButtons,
[{ text: "✉️ ÉCRIRE AU CLIENT", callback_data: `msg_client_${orderId}` }],
[{ text: "🔔 ARRIVÉE DANS 3 MIN", callback_data: `notify_arrival_${orderId}` }],
[{ text: "💰 ENCAISSER LA COMMANDE", callback_data: `c_in_${orderId}` }],
[{ text: "❌ ANNULER LA COMMANDE", callback_data: `cancel_order_${orderId}` }],
[{ text: "📋 RETOUR AU RÉCAPITULATIF", callback_data: "driver_view_recap" }]
];
} else {
keyboard = [
...baseButtons,
[{ text: "📋 RETOUR AU RÉCAPITULATIF", callback_data: "driver_view_recap" }]
];
}
try {
await ctx.deleteMessage();
} catch (e) {}
await ctx.reply(msg, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: keyboard }
});
ctx.answerCbQuery();
}
else if (data.startsWith('sh_v_ord_')) {
const orderId = data.split('_')[3];
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.answerCbQuery("Commande introuvable.");
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { query } = parseAddress(order?.address || '');
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const isMeetup = order.type === 'meetup';
const baseButtons = isMeetup ? [] : [
[
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
],
[{ text: "🚙 WAZE", url: wazeUrl }]
];
const userId = ctx.from.id.toString();
const { isEither: isManager } = isUserAdminOrManager(userId, ctx.from.username || null, settings);
const isAssignedDriver = String(order.driver_id) === userId;
let keyboard = [];
// If the user is the driver OR the manager, show the full action menu
if (isAssignedDriver || isManager) {
keyboard = [
...baseButtons,
[{ text: "✉️ ÉCRIRE AU CLIENT", callback_data: `msg_client_${orderId}` }],
[{ text: "🔔 ARRIVÉE DANS 3 MIN", callback_data: `notify_arrival_${orderId}` }],
[{ text: "💰 ENCAISSER LA COMMANDE", callback_data: `c_in_${orderId}` }],
[{ text: "❌ ANNULER LA COMMANDE", callback_data: `cancel_order_${orderId}` }],
[{ text: "📋 RETOUR AU RÉCAPITULATIF", callback_data: "driver_view_recap" }]
];
} else {
// For anyone else, just show the maps
keyboard = [
...baseButtons,
[{ text: "📋 RETOUR AU RÉCAPITULATIF", callback_data: "driver_view_recap" }]
];
}
await safeEdit(() => ctx.editMessageReplyMarkup({
inline_keyboard: keyboard
}));
ctx.answerCbQuery();
} catch (e) {
console.error('Error in sh_v_ord_:', e);
ctx.answerCbQuery("Erreur d'affichage.");
}
}
else if (data.startsWith('c_in_')) {
const orderId = data.split('_')[2];
await safeEdit(() => ctx.editMessageReplyMarkup({
inline_keyboard: [
[{ text: "⚠️ CONFIRMER L'ENCAISSEMENT ?", callback_data: `conf_c_in_${orderId}` }],
[{ text: "❌ ANNULER", callback_data: `sh_v_ord_${orderId}` }]
]
}));
ctx.answerCbQuery();
}
else if (data.startsWith('cancel_order_')) {
const orderId = data.split('_')[2];
await safeEdit(() => ctx.editMessageReplyMarkup({
inline_keyboard: [
[{ text: "⚠️ CONFIRMER L'ANNULATION ?", callback_data: `conf_cancel_${orderId}` }],
[{ text: "🔙 RETOUR", callback_data: `sh_v_ord_${orderId}` }]
]
}));
ctx.answerCbQuery();
}
else if (data.startsWith('conf_cancel_')) {
const orderId = data.split('_')[2];
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.answerCbQuery("Commande introuvable.");
const driverId = ctx.from.id.toString();
if (order.driver_id !== driverId) {
return ctx.answerCbQuery("❌ Seul le livreur en charge peut annuler cette commande.");
}
// Update status to cancelled
await supabase.from('orders').update({ status: 'cancelled' }).eq('id', orderId);
// 1. Notify client
if (order.client_telegram_id) {
const clientMsg = `❌ <b>Votre commande a été annulée.</b>\n\nNous sommes désolés pour ce désagrément. Si vous avez des questions, n'hésitez pas à contacter le manager.`;
await bot.telegram.sendMessage(order.client_telegram_id, clientMsg, { parse_mode: 'HTML' });
}
// 2. Update all notifications
const { data: notifications } = await supabase.from('order_notifications').select('*').eq('order_id', orderId);
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
if (notifications) {
for (const notif of notifications) {
try {
const isPrivilegedNotif = notif.driver_id === 'manager' || notif.driver_id === 'admin';
const statusSuffix = `\n\n❌ <b>COMMANDE ANNULÉE PAR LE LIVREUR</b>`;
const newText = await constructOrderMessage(orderId, isPrivilegedNotif, statusSuffix);
let targetChatId: string | null = null;
if (notif.driver_id === 'admin') {
targetChatId = formatChatId(adminId);
} else if (notif.driver_id === 'manager') {
targetChatId = formatChatId(settings?.manager_chat_id);
} else {
targetChatId = notif.driver_id;
}
if (targetChatId) {
await safeEdit(() => bot.telegram.editMessageText(targetChatId!, notif.message_id, undefined, newText, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: [] }
}));
}
} catch (e) {}
}
}
// 3. Update current message (for recap view)
try {
await ctx.deleteMessage();
} catch (e) {}
const recap = await generateDriverRecap(driverId);
await ctx.reply(`❌ <b>Commande annulée avec succès.</b>\n\n${recap.text}`, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
});
ctx.answerCbQuery("Commande annulée avec succès.");
} catch (err) {
console.error('Error cancelling order:', err);
ctx.answerCbQuery("Erreur lors de l'annulation.");
}
}
else if (data.startsWith('conf_c_in_')) {
const orderId = data.split('_')[3];
try {
const { data: order, error: fetchErr } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (fetchErr || !order) {
return ctx.answerCbQuery("Erreur : Commande introuvable.");
}
const clientId = order.client_telegram_id;
const total = order.total;
const collectorName = ctx.from.first_name || ctx.from.username || (order.type === 'meetup' ? "Un collaborateur" : "Un livreur");
// Update order status in DB
await supabase.from('orders').update({
status: 'completed',
completed_by_name: collectorName
}).eq('id', orderId);
// 1. Notify client
const clientMsg = `🏁 <b>Commande terminée !</b>\n\nMerci de votre confiance. Votre commande de <b>${total}€</b> a été encaissée avec succès. À bientôt !`;
if (clientId) {
await bot.telegram.sendMessage(clientId, clientMsg, { parse_mode: 'HTML' });
}
// 2. Update all notifications (Manager and Driver)
const { data: notifications } = await supabase.from('order_notifications').select('*').eq('order_id', orderId);
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
if (notifications) {
for (const notif of notifications) {
try {
const isPrivilegedNotif = notif.driver_id === 'manager' || notif.driver_id === 'admin';
const statusSuffix = order.type === 'meetup'
? `\n\n🤝 <b>TERMINÉ PAR :</b> ${collectorName}`
: `\n\n🏁 <b>TERMINÉ PAR :</b> ${collectorName}`;
const newText = await constructOrderMessage(orderId, isPrivilegedNotif, statusSuffix);
let keyboard = [];
if (isPrivilegedNotif) {
const { query } = parseAddress(order.address);
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const chatUrl = `tg://user?id=${clientId}`;
const isMeetup = order.type === 'meetup';
keyboard = isMeetup ? [[{ text: "💬 CONTACTER LE CLIENT", url: chatUrl }]] : [
[
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
],
[{ text: "🚙 WAZE", url: wazeUrl }],
[{ text: "💬 CONTACTER LE CLIENT", url: chatUrl }]
];
}
let targetChatId: string | null = null;
if (notif.driver_id === 'admin') {
targetChatId = formatChatId(adminId);
} else if (notif.driver_id === 'manager') {
targetChatId = formatChatId(settings?.manager_chat_id);
} else {
targetChatId = notif.driver_id;
}
if (targetChatId) {
await safeEdit(() => bot.telegram.editMessageText(targetChatId!, notif.message_id, undefined, newText, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: keyboard }
}));
}
} catch (e) {}
}
}
// 3. Update current message (for recap view)
try {
await ctx.deleteMessage();
} catch (e) {}
const recap = await generateDriverRecap(userId.toString());
await ctx.reply(`🏁 <b>Commande finalisée !</b>\n\n${recap.text}`, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: recap.keyboard }
});
ctx.answerCbQuery("Commande finalisée !");
} catch (err) {
console.error('Error in confirm_cash_in:', err);
ctx.answerCbQuery("Erreur lors de la finalisation.");
}
}
else if (data.startsWith('notify_arrival_')) {
const orderId = data.split('_')[2];
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (order && order.client_telegram_id) {
const isMeetup = order.type === 'meetup';
const driverName = ctx.from.first_name || ctx.from.username || (isMeetup ? "Votre collaborateur" : "Votre livreur");
const msg = isMeetup
? `🔔 <b>INFO MEET-UP :</b>\n\nVotre collaborateur <b>${driverName}</b> arrive au point de rendez-vous dans environ <b>3 minutes</b> ! 🤝\n\nVeuillez vous préparer pour la réception de votre commande de <b>${order.total}€</b>.`
: `🔔 <b>INFO LIVREUR :</b>\n\nVotre livreur <b>${driverName}</b> arrive dans environ <b>3 minutes</b> ! 🚀\n\nVeuillez vous préparer pour la réception de votre commande de <b>${order.total}€</b>.`;
const { data: settings } = await supabase.from('shop_settings').select('order_manager').eq('id', 1).single();
const managerUsername = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const clientButtons = [
[{
text: isMeetup ? "🤝 CONTACTER LE MEET-UP" : "🛵 CONTACTER LE LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
];
await bot.telegram.sendMessage(order.client_telegram_id, msg, {
parse_mode: 'HTML',
reply_markup: { inline_keyboard: clientButtons }
});
ctx.answerCbQuery("Client prévenu ! ✅");
}
} catch (e) {
console.error('Error notifying arrival:', e);
ctx.answerCbQuery("Erreur lors de la notification.");
}
}
else if (data.startsWith('msg_client_')) {
const orderId = data.split('_')[2];
userState[userId] = { step: 'awaiting_message_to_client', data: { orderId } };
ctx.reply("📝 Entrez le message que vous souhaitez envoyer au client :");
}
else if (data.startsWith('reply_to_driver_')) {
const orderId = data.split('_')[3];
userState[userId] = { step: 'awaiting_message_to_driver', data: { orderId } };
// Fetch order to know if it's a meetup
supabase.from('orders').select('type').eq('id', orderId).single().then(({ data: order }) => {
const isMeetup = order?.type === 'meetup';
ctx.reply(isMeetup ? "📝 Entrez votre réponse pour le collaborateur meetup :" : "📝 Entrez votre réponse pour le livreur :");
});
}
else if (data.startsWith('cat_')) {
const categoryId = data.split('_')[1];
const { data: category } = await supabase.from('categories').select('*').eq('id', categoryId).single();
userState[userId] = { step: 'awaiting_product_name', data: { category_id: categoryId, prices: [], type: category?.type || 'delivery' } };
ctx.reply(`Entrez le nom du produit (${category?.type === 'meetup' ? 'MEET-UP' : 'LIVRAISON'}) :`);
}
else if (data.startsWith('toggle_stock_')) {
const id = data.split('_')[2];
const { data: product } = await supabase.from('products').select('is_in_stock, type').eq('id', id).single();
const newStatus = product?.is_in_stock === false;
const { error } = await supabase.from('products').update({ is_in_stock: newStatus }).eq('id', id);
if (error) {
ctx.answerCbQuery(`Erreur : ${error.message}`);
} else {
ctx.answerCbQuery(newStatus ? "✅ Produit en stock !" : "🔴 Produit en rupture !");
// Refresh view based on type
const refreshData = product?.type === 'meetup' ? 'admin_manage_meetup_products' : 'admin_manage_products';
bot.handleUpdate({
callback_query: { ...ctx.callbackQuery, data: refreshData }
} as any);
}
}
else if (data.startsWith('del_cat_')) {
const id = data.split('_')[2];
const { data: category } = await supabase.from('categories').select('type').eq('id', id).single();
const cancelData = category?.type === 'meetup' ? 'admin_manage_meetup_categories' : 'admin_manage_categories';
await safeEdit(() => ctx.editMessageReplyMarkup({
inline_keyboard: [
[{ text: "⚠️ CONFIRMER SUPPRESSION CATÉGORIE ?", callback_data: `confirm_del_cat_${id}` }],
[{ text: "❌ ANNULER", callback_data: cancelData }]
]
}));
}
else if (data.startsWith('confirm_del_cat_')) {
const id = data.split('_')[3];
const { data: category } = await supabase.from('categories').select('type').eq('id', id).single();
const refreshData = category?.type === 'meetup' ? 'admin_manage_meetup_categories' : 'admin_manage_categories';
const { error } = await supabase.from('categories').delete().eq('id', id);
if (error) {
ctx.reply(`Erreur : ${error.message}`);
} else {
ctx.reply("Catégorie supprimée !");
bot.handleUpdate({
callback_query: { ...ctx.callbackQuery, data: refreshData }
} as any);
}
}
else if (data.startsWith('del_prod_')) {
const id = data.split('_')[2];
const { data: product } = await supabase.from('products').select('type').eq('id', id).single();
const cancelData = product?.type === 'meetup' ? 'admin_manage_meetup_products' : 'admin_manage_products';
await safeEdit(() => ctx.editMessageReplyMarkup({
inline_keyboard: [
[{ text: "⚠️ CONFIRMER SUPPRESSION PRODUIT ?", callback_data: `confirm_del_prod_${id}` }],
[{ text: "❌ ANNULER", callback_data: cancelData }]
]
}));
}
else if (data.startsWith('confirm_del_prod_')) {
const id = data.split('_')[3];
const { data: product } = await supabase.from('products').select('type').eq('id', id).single();
const refreshData = product?.type === 'meetup' ? 'admin_manage_meetup_products' : 'admin_manage_products';
const { error } = await supabase.from('products').delete().eq('id', id);
if (error) {
ctx.reply(`Erreur : ${error.message}`);
} else {
ctx.reply("Produit supprimé !");
bot.handleUpdate({
callback_query: { ...ctx.callbackQuery, data: refreshData }
} as any);
}
}
else if (data.startsWith('edit_prod_')) {
const id = data.split('_')[2];
userState[userId] = { step: 'awaiting_edit_choice', data: { id } };
ctx.reply("Que voulez-vous modifier ?", {
reply_markup: {
inline_keyboard: [
[{ text: "Nom", callback_data: `edit_field_name` }],
[{ text: "Description", callback_data: `edit_field_description` }],
[{ text: "Image", callback_data: `edit_field_image` }],
[{ text: "Prix/Quantités", callback_data: `edit_field_prices` }]
]
}
});
}
else if (data.startsWith('edit_field_')) {
const field = data.replace('edit_field_', '');
const state = userState[userId];
if (!state) return;
state.data.field = field;
state.step = 'awaiting_edit_value';
if (field === 'image') {
ctx.reply("Envoyez la nouvelle photo :");
} else if (field === 'prices') {
await showPriceManager(ctx, state.data.id);
} else {
ctx.reply(`Entrez la nouvelle valeur pour ${field} :`);
}
}
else if (data.startsWith('del_price_')) {
const priceId = data.split('_')[2];
// Fetch productId first to refresh manager
const { data: priceData } = await supabase.from('product_prices').select('product_id').eq('id', priceId).single();
const productId = priceData?.product_id;
const { error } = await supabase.from('product_prices').delete().eq('id', priceId);
if (error) {
ctx.answerCbQuery(`Erreur : ${error.message}`);
} else {
ctx.answerCbQuery("Tarif supprimé !");
if (productId) await showPriceManager(ctx, productId);
}
}
else if (data.startsWith('add_price_to_')) {
const productId = data.split('_')[3];
userState[userId] = { step: 'awaiting_new_price_for_product', data: { id: productId } };
ctx.reply("Entrez la quantité et le prix (ex: 1 10) :");
}
else if (data === 'finish_prices') {
const state = userState[userId];
if (!state || state.step !== 'awaiting_product_price_confirm') return;
// Save product and prices
const { data: product, error: pError } = await supabase.from('products').insert([{
category_id: state.data.category_id,
name: state.data.name,
description: state.data.description,
image_url: state.data.image_url,
type: state.data.type || 'delivery'
}]).select().single();
if (pError) {
ctx.reply(`Erreur produit : ${pError.message}`);
} else {
const pricesToInsert = state.data.prices.map((p: any) => ({
product_id: product.id,
quantity: p.quantity,
price: p.price
}));
await supabase.from('product_prices').insert(pricesToInsert);
ctx.reply(`Produit "${state.data.name}" ajouté avec succès avec ${pricesToInsert.length} tarifs !`);
}
delete userState[userId];
}
else if (data === 'add_more_prices') {
const state = userState[userId];
if (!state) return;
state.step = 'awaiting_product_price_qty';
ctx.reply("Entrez la quantité et le prix (ex: 2 18) :");
}
ctx.answerCbQuery();
});
bot.on('text', async (ctx) => {
const userId = ctx.from.id;
const state = userState[userId];
console.log(`Text received from ${userId}: ${ctx.message.text}, state: ${state?.step || 'none'}`);
if (!state) return;
if (state.step === 'awaiting_message_to_client') {
const orderId = state.data.orderId;
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (order && order.client_telegram_id) {
const isMeetup = order.type === 'meetup';
const driverName = ctx.from.first_name || ctx.from.username || (isMeetup ? "Votre collaborateur" : "Votre livreur");
const clientMsg = isMeetup
? `💬 <b>MESSAGE DE VOTRE COLLABORATEUR (${driverName}) :</b>\n\n${ctx.message.text}`
: `💬 <b>MESSAGE DE VOTRE LIVREUR (${driverName}) :</b>\n\n${ctx.message.text}`;
await bot.telegram.sendMessage(order.client_telegram_id, clientMsg, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{
text: isMeetup ? "✍️ RÉPONDRE AU COLLABORATEUR" : "✍️ RÉPONDRE AU LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
]
}
});
ctx.reply("✅ Message envoyé au client !");
} else {
ctx.reply("❌ Impossible d'envoyer le message : client introuvable.");
}
} catch (e) {
console.error('Error sending message to client:', e);
ctx.reply("❌ Erreur lors de l'envoi du message.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_message_to_driver') {
const orderId = state.data.orderId;
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.reply("❌ Commande introuvable.");
const clientName = ctx.from.first_name || "Le client";
const messageText = ctx.message.text;
if (order.driver_id && order.driver_id !== 'manager') {
// Send to assigned driver
const isMeetup = order.type === 'meetup';
const driverMsg = `💬 <b>RÉPONSE DU CLIENT (${clientName}) :</b>\n\n${messageText}`;
await bot.telegram.sendMessage(order.driver_id, driverMsg, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply(isMeetup ? "✅ Votre réponse a été envoyée au collaborateur !" : "✅ Votre réponse a été envoyée au livreur !");
} else {
// Send to manager (either driver_id is 'manager' or null)
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const managerMsg = `💬 <b>RÉPONSE DU CLIENT (${clientName}) [Commande #${orderId}] :</b>\n\n${messageText}`;
await bot.telegram.sendMessage(targetChatId, managerMsg, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply("✅ Votre réponse a été envoyée au manager !");
}
} catch (e) {
console.error('Error sending message to driver:', e);
ctx.reply("❌ Erreur lors de l'envoi de la réponse.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_referral_info') {
const referralInfo = ctx.message.text;
const userId = ctx.from.id.toString();
const username = ctx.from.username ? `@${ctx.from.username}` : 'Aucun';
const firstName = ctx.from.first_name || 'Inconnu';
try {
// Update user status to pending
await supabase.from('bot_users').update({
verification_status: 'pending',
referral_info: referralInfo
}).eq('telegram_id', userId);
// Notify manager
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const managerMsg = `🔔 <b>NOUVELLE DEMANDE DE VÉRIFICATION</b>\n\n` +
`👤 <b>Client :</b> ${firstName} (${username})\n` +
`🆔 <b>ID :</b> <code>${userId}</code>\n` +
`🔗 <b>Référent :</b> ${referralInfo}\n\n` +
`Que souhaitez-vous faire ?`;
await bot.telegram.sendMessage(targetChatId, managerMsg, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[
{ text: "✅ ACCEPTER", callback_data: `approve_user_${userId}` },
{ text: "❌ REFUSER", callback_data: `reject_user_${userId}` }
],
[{ text: "✍️ ÉCRIRE AU CLIENT", callback_data: `msg_client_v_${userId}` }]
]
}
});
ctx.reply("✅ <b>DEMANDE ENVOYÉE</b>\n\nVos informations ont été transmises au manager. Veuillez patienter pendant la vérification.\n\nVous recevrez un message ici dès que votre accès sera validé.", {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ ÉCRIRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
delete userState[userId];
} catch (e) {
console.error('Error in verification flow:', e);
ctx.reply("❌ Une erreur est survenue lors de l'envoi de votre demande. Veuillez réessayer plus tard.");
}
}
else if (state.step === 'awaiting_verification_msg_to_manager') {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const clientName = ctx.from.first_name || ctx.from.username || "Le client";
await bot.telegram.sendMessage(targetChatId, `💬 <b>MESSAGE DU CLIENT EN VÉRIFICATION (${clientName}) :</b>\n\n${ctx.message.text}`, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU CLIENT", callback_data: `msg_client_v_${ctx.from.id}` }]
]
}
});
ctx.reply("✅ Message envoyé au manager !");
delete userState[ctx.from.id];
}
else if (state.step === 'awaiting_verification_msg_to_client') {
const targetUserId = state.data.targetUserId;
await bot.telegram.sendMessage(targetUserId, `💬 <b>MESSAGE DU MANAGER :</b>\n\n${ctx.message.text}`, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
ctx.reply("✅ Message envoyé au client !");
delete userState[ctx.from.id];
}
});
bot.on('photo', async (ctx) => {
const userId = ctx.from.id;
const state = userState[userId];
if (!state) return;
// 1. PRODUCT & SHOP MANAGEMENT (Existing logic)
if (state.step === 'awaiting_product_image' || (state.step === 'awaiting_edit_value' && state.data.field === 'image') || (state.step === 'awaiting_shop_edit' && state.data.field === 'logo')) {
try {
ctx.reply("Téléchargement de l'image... ⏳");
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const fileLink = await ctx.telegram.getFileLink(photo.file_id);
const axios = (await import('axios')).default;
const response = await axios.get(fileLink.href, { responseType: 'arraybuffer' });
const buffer = Buffer.from(response.data, 'binary');
const fileName = `${Date.now()}_${photo.file_id}.jpg`;
const { error } = await supabase.storage.from('product-images').upload(fileName, buffer, { contentType: 'image/jpeg' });
if (error) throw error;
const { data: { publicUrl } } = supabase.storage.from('product-images').getPublicUrl(fileName);
if (state.step === 'awaiting_shop_edit') {
await supabase.from('shop_settings').update({ logo_url: publicUrl }).eq('id', 1);
ctx.reply("Logo mis à jour ! ✅\n\n💡 Note : Assurez-vous que votre bucket 'product-images' est configuré comme 'Public' dans Supabase Storage pour que les images s'affichent.");
delete userState[userId];
} else if (state.step === 'awaiting_edit_value') {
await supabase.from('products').update({ image_url: publicUrl }).eq('id', state.data.id);
ctx.reply("Image mise à jour ! ✅\n\n💡 Note : Assurez-vous que votre bucket 'product-images' est configuré comme 'Public' dans Supabase Storage.");
delete userState[userId];
} else {
state.data.image_url = publicUrl;
state.step = 'awaiting_product_price_qty';
ctx.reply("Image enregistrée ! ✅\n\n💡 Note : Assurez-vous que votre bucket 'product-images' est configuré comme 'Public' dans Supabase Storage.\n\nEntrez maintenant la quantité et le prix (ex: 1 10) :");
}
} catch (err: any) {
ctx.reply(`Erreur : ${err.message}`);
}
}
// 2. CHAT ROUTING (New logic)
else if (state.step === 'awaiting_message_to_client') {
const orderId = state.data.orderId;
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const caption = ctx.message.caption || "";
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (order && order.client_telegram_id) {
const isMeetup = order.type === 'meetup';
const driverName = ctx.from.first_name || ctx.from.username || (isMeetup ? "Votre collaborateur" : "Votre livreur");
const clientMsg = isMeetup
? `📸 <b>PHOTO DE VOTRE COLLABORATEUR (${driverName}) :</b>\n\n${caption}`
: `📸 <b>PHOTO DE VOTRE LIVREUR (${driverName}) :</b>\n\n${caption}`;
await bot.telegram.sendPhoto(order.client_telegram_id, photo.file_id, {
caption: clientMsg,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{
text: isMeetup ? "✍️ RÉPONDRE AU COLLABORATEUR" : "✍️ RÉPONDRE AU LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
]
}
});
ctx.reply("✅ Photo envoyée au client !");
}
} catch (e) {
console.error('Error sending photo to client:', e);
ctx.reply("❌ Erreur lors de l'envoi de la photo.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_message_to_driver') {
const orderId = state.data.orderId;
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const caption = ctx.message.caption || "";
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.reply("❌ Commande introuvable.");
const clientName = ctx.from.first_name || "Le client";
const driverMsg = `📸 <b>PHOTO DU CLIENT (${clientName}) :</b>\n\n${caption}`;
if (order.driver_id && order.driver_id !== 'manager') {
await bot.telegram.sendPhoto(order.driver_id, photo.file_id, {
caption: driverMsg,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply(order.type === 'meetup' ? "✅ Votre photo a été envoyée au collaborateur !" : "✅ Votre photo a été envoyée au livreur !");
} else {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
await bot.telegram.sendPhoto(targetChatId, photo.file_id, {
caption: `📸 <b>PHOTO DU CLIENT (${clientName}) [Commande #${orderId}] :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply("✅ Votre photo a été envoyée au manager !");
}
} catch (e) {
console.error('Error sending photo to driver:', e);
ctx.reply("❌ Erreur lors de l'envoi de la photo.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_verification_msg_to_manager') {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const clientName = ctx.from.first_name || ctx.from.username || "Le client";
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const caption = ctx.message.caption || "";
await bot.telegram.sendPhoto(targetChatId, photo.file_id, {
caption: `📸 <b>PHOTO DU CLIENT EN VÉRIFICATION (${clientName}) :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU CLIENT", callback_data: `msg_client_v_${ctx.from.id}` }]
]
}
});
ctx.reply("✅ Photo envoyée au manager !");
delete userState[userId];
}
else if (state.step === 'awaiting_verification_msg_to_client') {
const targetUserId = state.data.targetUserId;
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const caption = ctx.message.caption || "";
await bot.telegram.sendPhoto(targetUserId, photo.file_id, {
caption: `📸 <b>PHOTO DU MANAGER :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
ctx.reply("✅ Photo envoyée au client !");
delete userState[userId];
}
else if (state.step === 'awaiting_referral_info') {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const clientName = ctx.from.first_name || ctx.from.username || "Le client";
const photo = ctx.message.photo[ctx.message.photo.length - 1];
const caption = ctx.message.caption || "";
const userIdStr = ctx.from.id.toString();
await bot.telegram.sendPhoto(targetChatId, photo.file_id, {
caption: `🔔 <b>NOUVELLE PHOTO DE VÉRIFICATION</b>\n\n👤 <b>Client :</b> ${clientName}\n🆔 <b>ID :</b> <code>${userIdStr}</code>\n🔗 <b>Infos :</b> ${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[
{ text: "✅ ACCEPTER", callback_data: `approve_user_${userIdStr}` },
{ text: "❌ REFUSER", callback_data: `reject_user_${userIdStr}` }
],
[{ text: "✍️ ÉCRIRE AU CLIENT", callback_data: `msg_client_v_${userIdStr}` }]
]
}
});
// Also update status to pending if not already
await supabase.from('bot_users').update({
verification_status: 'pending',
referral_info: caption || "Photo envoyée"
}).eq('telegram_id', userIdStr);
ctx.reply("✅ <b>PHOTO ENVOYÉE</b>\n\nVotre photo de vérification a été transmise au manager. Veuillez patienter.", {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ ÉCRIRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
delete userState[userId];
}
});
bot.on('video', async (ctx) => {
const userId = ctx.from.id;
const state = userState[userId];
if (!state) return;
// CHAT ROUTING FOR VIDEOS
if (state.step === 'awaiting_message_to_client') {
const orderId = state.data.orderId;
const video = ctx.message.video;
const caption = ctx.message.caption || "";
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (order && order.client_telegram_id) {
const isMeetup = order.type === 'meetup';
const driverName = ctx.from.first_name || ctx.from.username || (isMeetup ? "Votre collaborateur" : "Votre livreur");
const clientMsg = isMeetup
? `🎥 <b>VIDÉO DE VOTRE COLLABORATEUR (${driverName}) :</b>\n\n${caption}`
: `🎥 <b>VIDÉO DE VOTRE LIVREUR (${driverName}) :</b>\n\n${caption}`;
await bot.telegram.sendVideo(order.client_telegram_id, video.file_id, {
caption: clientMsg,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{
text: isMeetup ? "✍️ RÉPONDRE AU COLLABORATEUR" : "✍️ RÉPONDRE AU LIVREUR",
callback_data: `reply_to_driver_${orderId}`
}]
]
}
});
ctx.reply("✅ Vidéo envoyée au client !");
}
} catch (e) {
console.error('Error sending video to client:', e);
ctx.reply("❌ Erreur lors de l'envoi de la vidéo.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_message_to_driver') {
const orderId = state.data.orderId;
const video = ctx.message.video;
const caption = ctx.message.caption || "";
try {
const { data: order } = await supabase.from('orders').select('*').eq('id', orderId).single();
if (!order) return ctx.reply("❌ Commande introuvable.");
const clientName = ctx.from.first_name || "Le client";
const driverMsg = `🎥 <b>VIDÉO DU CLIENT (${clientName}) :</b>\n\n${caption}`;
if (order.driver_id && order.driver_id !== 'manager') {
await bot.telegram.sendVideo(order.driver_id, video.file_id, {
caption: driverMsg,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply(order.type === 'meetup' ? "✅ Votre vidéo a été envoyée au collaborateur !" : "✅ Votre vidéo a été envoyée au livreur !");
} else {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
await bot.telegram.sendVideo(targetChatId, video.file_id, {
caption: `🎥 <b>VIDÉO DU CLIENT (${clientName}) [Commande #${orderId}] :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✉️ RÉPONDRE AU CLIENT", callback_data: `msg_client_${orderId}` }]
]
}
});
ctx.reply("✅ Votre vidéo a été envoyée au manager !");
}
} catch (e) {
console.error('Error sending video to driver:', e);
ctx.reply("❌ Erreur lors de l'envoi de la vidéo.");
}
delete userState[userId];
}
else if (state.step === 'awaiting_verification_msg_to_manager') {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const clientName = ctx.from.first_name || ctx.from.username || "Le client";
const video = ctx.message.video;
const caption = ctx.message.caption || "";
await bot.telegram.sendVideo(targetChatId, video.file_id, {
caption: `🎥 <b>VIDÉO DU CLIENT EN VÉRIFICATION (${clientName}) :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU CLIENT", callback_data: `msg_client_v_${ctx.from.id}` }]
]
}
});
ctx.reply("✅ Vidéo envoyée au manager !");
delete userState[userId];
}
else if (state.step === 'awaiting_verification_msg_to_client') {
const targetUserId = state.data.targetUserId;
const video = ctx.message.video;
const caption = ctx.message.caption || "";
await bot.telegram.sendVideo(targetUserId, video.file_id, {
caption: `🎥 <b>VIDÉO DU MANAGER :</b>\n\n${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ RÉPONDRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
ctx.reply("✅ Vidéo envoyée au client !");
delete userState[userId];
}
else if (state.step === 'awaiting_referral_info') {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const targetChatId = settings?.manager_chat_id || adminId;
const clientName = ctx.from.first_name || ctx.from.username || "Le client";
const video = ctx.message.video;
const caption = ctx.message.caption || "";
const userIdStr = ctx.from.id.toString();
await bot.telegram.sendVideo(targetChatId, video.file_id, {
caption: `🔔 <b>NOUVELLE VIDÉO DE VÉRIFICATION</b>\n\n👤 <b>Client :</b> ${clientName}\n🆔 <b>ID :</b> <code>${userIdStr}</code>\n🔗 <b>Infos :</b> ${caption}`,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[
{ text: "✅ ACCEPTER", callback_data: `approve_user_${userIdStr}` },
{ text: "❌ REFUSER", callback_data: `reject_user_${userIdStr}` }
],
[{ text: "✍️ ÉCRIRE AU CLIENT", callback_data: `msg_client_v_${userIdStr}` }]
]
}
});
// Also update status to pending if not already
await supabase.from('bot_users').update({
verification_status: 'pending',
referral_info: caption || "Vidéo envoyée"
}).eq('telegram_id', userIdStr);
ctx.reply("✅ <b>VIDÉO ENVOYÉE</b>\n\nVotre vidéo de vérification a été transmise au manager. Veuillez patienter.", {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "✍️ ÉCRIRE AU MANAGER", callback_data: "contact_manager_verification" }]
]
}
});
delete userState[userId];
}
});
// Error handling
bot.catch((err: any, ctx) => {
console.error(`Telegraf error for ${ctx.updateType}`, err);
const errorMessage = err.message || String(err);
ctx.reply(`Une erreur est survenue lors du traitement de votre demande.\n\nErreur : ${errorMessage}`);
});
// Enable graceful stop
const handleShutdown = (signal: string) => {
console.log(`Received ${signal}, stopping bot...`);
bot.stop(signal);
process.exit(0);
};
process.once('SIGINT', () => handleShutdown('SIGINT'));
process.once('SIGTERM', () => handleShutdown('SIGTERM'));
// --- Express Server ---
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
// Webhook for Telegram Bot
if (appUrl && botToken) {
const webhookPath = `/api/webhook/${botToken}`;
app.post(webhookPath, (req, res) => {
bot.handleUpdate(req.body, res);
});
try {
// Clear webhook and drop pending updates to resolve conflicts
await bot.telegram.deleteWebhook({ drop_pending_updates: true });
await bot.telegram.setWebhook(`${appUrl}${webhookPath}`);
console.log(`Bot: Webhook set to ${appUrl}${webhookPath} ✅`);
} catch (err) {
console.error('Bot: Error setting webhook:', err);
}
} else if (botToken) {
// Fallback to polling for local development
bot.launch().then(() => {
console.log('Bot: Started with polling (no appUrl found) ✅');
}).catch(err => {
console.error('Bot: Polling error:', err);
});
}
// API routes
app.get('/api/config', async (req, res) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
try {
let { data: settings, error: fetchError } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
// If table doesn't exist or other error, fallback to defaults
if (fetchError || !settings) {
console.log('Shop settings not found or table missing, using defaults');
const defaultSettings = {
id: 1,
name: 'Shop',
description: 'Bienvenue dans notre boutique Telegram',
order_manager: process.env.VITE_ORDER_MANAGER_USERNAME || 'manager',
accent_color: '#10B981',
is_auto_broadcast_enabled: true,
is_open: true,
is_meetup_enabled: false,
is_verification_enabled: false,
order_dispatch_mode: 'private',
delivery_group_id: '',
meetup_group_id: ''
};
// Try to bootstrap if it was just a missing row, but ignore if table is missing
if (!settings && !fetchError) {
await supabase.from('shop_settings').insert([defaultSettings]);
}
settings = defaultSettings as any;
}
res.json({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_ANON_KEY,
orderManager: (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', ''),
shopName: settings?.name || 'Shop',
shopDescription: settings?.description || '',
shopLogo: settings?.logo_url || '',
shopBanner: settings?.banner_url || '',
isOpen: settings?.is_open !== false,
isMeetupEnabled: settings?.is_meetup_enabled === true,
isVerificationEnabled: settings?.is_verification_enabled === true,
welcomeMessage: settings?.welcome_message || '',
infoText: settings?.info_text || '',
channelUrl: settings?.channel_url || 'https://t.me/hftfrance',
managerChatId: settings?.manager_chat_id || '',
adminId: adminId,
isAutoBroadcastEnabled: settings?.is_auto_broadcast_enabled !== false,
orderDispatchMode: settings?.order_dispatch_mode || 'private',
deliveryGroupId: settings?.delivery_group_id || '',
meetupGroupId: settings?.meetup_group_id || '',
accentColor: settings?.accent_color || '#10B981'
});
} catch (err) {
console.error('Config API Error:', err);
res.json({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_ANON_KEY,
orderManager: process.env.VITE_ORDER_MANAGER_USERNAME,
shopName: 'Shop',
shopDescription: '',
shopLogo: '',
isOpen: true,
isMeetupEnabled: false,
isVerificationEnabled: false,
welcomeMessage: '',
infoText: '',
channelUrl: 'https://t.me/hftfrance',
managerChatId: '',
adminId: adminId,
accentColor: '#10B981'
});
}
});
app.post('/api/admin/broadcast', async (req, res) => {
const { message, target, userId, username, photoUrl } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId || '', username || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const sendMsg = async (chatId: string, isChannel: boolean = false) => {
const botLink = botUsername ? `https://t.me/${botUsername}` : appUrl;
const keyboard = Markup.inlineKeyboard([
[isChannel
? Markup.button.url('🟢 COMMANDER 🟢', botLink)
: Markup.button.webApp('🟢 COMMANDER 🟢', appUrl)
]
]);
if (photoUrl) {
await bot.telegram.sendPhoto(chatId, photoUrl, {
caption: message,
parse_mode: 'HTML',
...keyboard
});
} else {
await bot.telegram.sendMessage(chatId, message, {
parse_mode: 'HTML',
...keyboard
});
}
};
if (target === 'clients' || target === 'both') {
const { data: users } = await supabase.from('bot_users').select('telegram_id');
if (users) {
for (const user of users) {
try {
await sendMsg(user.telegram_id, false);
} catch (e) {
console.warn(`Could not send broadcast to ${user.telegram_id}:`, e);
}
}
}
}
if (target === 'channels' || target === 'both') {
const { data: chats } = await supabase.from('integrated_chats').select('chat_id');
if (chats && chats.length > 0) {
for (const chat of chats) {
try {
await sendMsg(chat.chat_id, true);
} catch (e) {
console.warn(`Could not send broadcast to integrated chat ${chat.chat_id}:`, e);
}
}
} else if (settings?.channel_url) {
// Fallback to settings channel if no integrated chats found
const channelId = settings.channel_url.split('/').pop();
if (channelId) {
try {
await sendMsg(`@${channelId}`, true);
} catch (e) {
console.warn(`Could not send broadcast to settings channel @${channelId}:`, e);
}
}
}
}
res.json({ success: true });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/admin/send-message', async (req, res) => {
const { userId, username, message, chatId } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId || '', username || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
// Send only to the requester or the specified chatId
const target = chatId || userId;
if (!target) {
return res.status(400).json({ error: 'No target specified' });
}
try {
await bot.telegram.sendMessage(target, message, { parse_mode: 'HTML' });
} catch (e) {
console.error(`Failed to send message to ${target}:`, e);
return res.status(500).json({ error: `Failed to send message: ${e.message}` });
}
res.json({ success: true });
} catch (err: any) {
console.error('Send Message API Error:', err);
res.status(500).json({ error: err.message });
}
});
app.post('/api/admin/send-document', async (req, res) => {
const { userId, username, content, filename, caption } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId || '', username || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
// Send only to the requester
const target = userId;
if (!target) {
return res.status(400).json({ error: 'No target specified' });
}
const buffer = Buffer.from(content, 'utf-8');
try {
await bot.telegram.sendDocument(target, { source: buffer, filename }, { caption });
} catch (e) {
console.error(`Failed to send document to ${target}:`, e);
return res.status(500).json({ error: `Failed to send document: ${e.message}` });
}
res.json({ success: true });
} catch (err: any) {
console.error('Send Document API Error:', err);
res.status(500).json({ error: err.message });
}
});
app.get('/api/admin/data', async (req, res) => {
const { userId, username } = req.query;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId as string || '', username as string || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const [
{ data: usrs },
{ data: ords },
{ data: drvs },
{ data: wrks }
] = await Promise.all([
supabase.from('bot_users').select('*').order('created_at', { ascending: false }),
supabase.from('orders').select('*').order('created_at', { ascending: false }),
supabase.from('drivers').select('*').order('created_at', { ascending: false }),
supabase.from('meetup_workers').select('*').order('created_at', { ascending: false })
]);
res.json({
botUsers: usrs || [],
orders: ords || [],
drivers: drvs || [],
workers: wrks || []
});
} catch (error: any) {
console.error('Admin Data API Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/team', async (req, res) => {
const { userId, username, type, tgId, name } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const table = type === 'driver' ? 'drivers' : 'meetup_workers';
const { data, error } = await supabase.from(table).insert([{ telegram_id: tgId, first_name: name }]).select();
if (error) throw error;
res.json({ success: true, data: data[0] });
} catch (error: any) {
console.error('Add Team Member Error:', error);
res.status(500).json({ error: error.message });
}
});
app.delete('/api/admin/team', async (req, res) => {
const { userId, username, type, id } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const table = type === 'driver' ? 'drivers' : 'meetup_workers';
const { error } = await supabase.from(table).delete().eq('id', id);
if (error) throw error;
res.json({ success: true });
} catch (error: any) {
console.error('Delete Team Member Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/settings', async (req, res) => {
const { userId, username, settings } = req.body;
try {
const { data: currentSettings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, currentSettings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const { error } = await supabase.from('shop_settings').update(settings).eq('id', 1);
if (error) throw error;
res.json({ success: true });
} catch (error: any) {
console.error('Update Settings Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/verify-user', async (req, res) => {
const { userId, username, targetUserId, isVerified } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
const { error } = await supabase.from('bot_users').update({ is_verified: isVerified }).eq('id', targetUserId);
if (error) throw error;
res.json({ success: true });
} catch (error: any) {
console.error('Verify User Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/products', async (req, res) => {
const { userId, username, action, product, productId, updates } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
if (action === 'insert') {
const { data, error } = await supabase.from('products').insert([product]).select().single();
if (error) throw error;
return res.json({ success: true, data });
} else if (action === 'update') {
const { error } = await supabase.from('products').update(updates).eq('id', productId);
if (error) throw error;
return res.json({ success: true });
} else if (action === 'delete') {
const { error } = await supabase.from('products').delete().eq('id', productId);
if (error) throw error;
return res.json({ success: true });
}
res.status(400).json({ error: 'Invalid action' });
} catch (error: any) {
console.error('Product Management Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/categories', async (req, res) => {
const { userId, username, action, category, categoryId, updates } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
if (action === 'insert') {
const { data, error } = await supabase.from('categories').insert([category]).select().single();
if (error) throw error;
return res.json({ success: true, data });
} else if (action === 'update') {
const { error } = await supabase.from('categories').update(updates).eq('id', categoryId);
if (error) throw error;
return res.json({ success: true });
} else if (action === 'delete') {
const { error } = await supabase.from('categories').delete().eq('id', categoryId);
if (error) throw error;
return res.json({ success: true });
}
res.status(400).json({ error: 'Invalid action' });
} catch (error: any) {
console.error('Category Management Error:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/prices', async (req, res) => {
const { userId, username, action, price, priceId } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId, username, settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
if (action === 'insert') {
const { data, error } = await supabase.from('product_prices').insert([price]).select().single();
if (error) throw error;
return res.json({ success: true, data });
} else if (action === 'delete') {
const { error } = await supabase.from('product_prices').delete().eq('id', priceId);
if (error) throw error;
return res.json({ success: true });
}
res.status(400).json({ error: 'Invalid action' });
} catch (error: any) {
console.error('Price Management Error:', error);
res.status(500).json({ error: error.message });
}
});
app.get('/api/admin/stats', async (req, res) => {
const { userId, username } = req.query;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId as string || '', username as string || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
// Only count orders that are NOT yet reported
const { data: orders } = await supabase.from('orders').select('*').neq('status', 'reported');
const { data: clients } = await supabase.from('bot_users').select('id', { count: 'exact' });
const { data: drivers } = await supabase.from('drivers').select('*');
const { data: workers } = await supabase.from('meetup_workers').select('*');
const totalRevenue = orders?.filter(o => o.status === 'completed').reduce((acc, o) => acc + (o.total || 0), 0) || 0;
const statusStats = {
pending: orders?.filter(o => o.status === 'pending').length || 0,
taken: orders?.filter(o => o.status === 'validated').length || 0,
completed: orders?.filter(o => o.status === 'completed').length || 0,
cancelled: orders?.filter(o => o.status === 'cancelled').length || 0
};
// Stats per driver
const driverStats = drivers?.map(d => {
const driverOrders = orders?.filter(o => o.driver_id === d.telegram_id && o.status === 'completed' && o.type !== 'meetup') || [];
return {
id: d.telegram_id,
username: d.username,
name: d.first_name,
count: driverOrders.length,
revenue: driverOrders.reduce((acc, o) => acc + (o.total || 0), 0)
};
}) || [];
// Stats per worker
const workerStats = workers?.map(w => {
const workerOrders = orders?.filter(o => o.driver_id === w.telegram_id && o.status === 'completed' && o.type === 'meetup') || [];
return {
id: w.telegram_id,
username: w.username,
name: w.first_name,
count: workerOrders.length,
revenue: workerOrders.reduce((acc, o) => acc + (o.total || 0), 0)
};
}) || [];
// Stats per product
const productStats: Record<string, { qty: number, revenue: number, formats: Record<string, number> }> = {};
const completedOrders = orders?.filter(o => o.status === 'completed') || [];
completedOrders.forEach(o => {
if (o.items && Array.isArray(o.items)) {
o.items.forEach((item: any) => {
const name = item.productName || item.name || 'Inconnu';
const qty = Number(item.count) || Number(item.quantity) || 1;
const price = Number(item.price) || 0;
const format = item.quantityLabel || 'N/A';
if (!productStats[name]) {
productStats[name] = { qty: 0, revenue: 0, formats: {} };
}
productStats[name].qty += qty;
productStats[name].revenue += (price * qty);
productStats[name].formats[format] = (productStats[name].formats[format] || 0) + qty;
});
}
});
res.json({
ordersCount: orders?.length || 0,
totalRevenue,
clientsCount: clients?.length || 0,
statusStats,
driverStats,
workerStats,
productStats
});
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/admin/toggle-broadcast', async (req, res) => {
const { userId, username, isEnabled } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId || '', username || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
await supabase.from('shop_settings').update({ is_auto_broadcast_enabled: isEnabled }).eq('id', 1);
res.json({ success: true });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/admin/toggle-shop', async (req, res) => {
const { userId, username, isOpen } = req.body;
try {
const { data: settings } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
const { isEither } = isUserAdminOrManager(userId || '', username || '', settings);
if (!isEither) {
return res.status(403).json({ error: 'Unauthorized' });
}
// Update shop status
await supabase.from('shop_settings').update({ is_open: isOpen }).eq('id', 1);
if (isOpen) {
// Broadcast opening message to all clients
const shopName = settings?.name || 'Shop';
const logoUrl = settings?.logo_url;
const isAutoBroadcast = settings?.is_auto_broadcast_enabled !== false;
if (isAutoBroadcast) {
const { data: users } = await supabase.from('bot_users').select('telegram_id');
if (users) {
const message = `Le shop ${shopName} est ouvert ! 🟢\n\nVenez passer vos commandes dès maintenant !`;
const keyboard = Markup.inlineKeyboard([
[Markup.button.webApp('🟢 COMMANDER 🟢', appUrl)]
]);
for (const user of users) {
try {
if (logoUrl) {
await bot.telegram.sendPhoto(user.telegram_id, logoUrl, {
caption: message,
parse_mode: 'HTML',
...keyboard
});
} else {
await bot.telegram.sendMessage(user.telegram_id, message, {
parse_mode: 'HTML',
...keyboard
});
}
} catch (e) {
console.warn(`Could not send opening broadcast to ${user.telegram_id}:`, e);
}
}
}
}
} else {
// Generate and send report on close
const { data: orders } = await supabase.from('orders').select('*').neq('status', 'reported');
const { data: drivers } = await supabase.from('drivers').select('*');
const { data: workers } = await supabase.from('meetup_workers').select('*');
const completedOrders = orders?.filter(o => o.status === 'completed') || [];
const takenOrders = orders?.filter(o => o.status === 'validated') || [];
const cancelledOrders = orders?.filter(o => o.status === 'cancelled') || [];
const pendingOrders = orders?.filter(o => o.status === 'pending') || [];
const totalRevenue = completedOrders.reduce((acc, o) => acc + (o.total || 0), 0) || 0;
let report = `📊 RAPPORT DE SESSION (FERMETURE)\n\n` +
`📦 TOTAL COMMANDES: ${orders?.length || 0}\n` +
`✅ EFFECTUÉES: ${completedOrders.length}\n` +
`🚚 EN COURS: ${takenOrders.length}\n` +
`❌ ANNULÉES: ${cancelledOrders.length}\n` +
`⏳ EN ATTENTE: ${pendingOrders.length}\n` +
`💰 CA TOTAL: ${totalRevenue}€\n\n`;
if (drivers && drivers.length > 0) {
report += `🚚 LIVREURS (🚀):\n`;
drivers.forEach(d => {
const dOrders = completedOrders.filter(o => o.driver_id === d.telegram_id && o.type !== 'meetup');
if (dOrders.length > 0) {
report += `- ${d.first_name || d.username || d.telegram_id}: ${dOrders.length} livr. (${dOrders.reduce((acc, o) => acc + (o.total || 0), 0)}€)\n`;
}
});
report += `\n`;
}
if (workers && workers.length > 0) {
report += `🤝 MEETUP (🤝):\n`;
workers.forEach(w => {
const wOrders = completedOrders.filter(o => o.driver_id === w.telegram_id && o.type === 'meetup');
if (wOrders.length > 0) {
report += `- ${w.first_name || w.username || w.telegram_id}: ${wOrders.length} rdv (${wOrders.reduce((acc, o) => acc + (o.total || 0), 0)}€)\n`;
}
});
report += `\n`;
}
// Stats per product
const productStats: Record<string, { qty: number, revenue: number, formats: Record<string, number> }> = {};
completedOrders.forEach(o => {
if (o.items && Array.isArray(o.items)) {
o.items.forEach((item: any) => {
const name = item.productName || item.name || 'Inconnu';
const qty = Number(item.count) || Number(item.quantity) || 1;
const price = Number(item.price) || 0;
const format = item.quantityLabel || 'N/A';
if (!productStats[name]) {
productStats[name] = { qty: 0, revenue: 0, formats: {} };
}
productStats[name].qty += qty;
productStats[name].revenue += (price * qty);
productStats[name].formats[format] = (productStats[name].formats[format] || 0) + qty;
});
}
});
const productEntries = Object.entries(productStats);
if (productEntries.length > 0) {
report += `📦 DÉTAIL DES VENTES :\n`;
productEntries.sort((a, b) => b[1].revenue - a[1].revenue).forEach(([name, data]) => {
report += `• ${name}\n └ Qté : x${data.qty} | Total : ${data.revenue}€\n`;
const formats = Object.entries(data.formats);
if (formats.length > 0) {
report += ` Formats : ${formats.map(([f, q]) => `${f} (x${q})`).join(', ')}\n`;
}
});
report += `\n`;
}
report += `Généré le ${new Date().toLocaleString()}`;
// Send session report only to the requester
if (userId) {
try {
await bot.telegram.sendMessage(userId, report, { parse_mode: 'HTML' });
} catch (e) {
console.error(`Failed to send session report to requester ${userId}:`, e);
}
}
// Mark reported orders
if (orders && orders.length > 0) {
const orderIds = orders.map(o => o.id);
await supabase.from('orders').update({ status: 'reported' }).in('id', orderIds);
}
}
res.json({ success: true });
} catch (err: any) {
console.error('Toggle Shop API Error:', err);
res.status(500).json({ error: err.message });
}
});
app.post("/api/orders", async (req, res) => {
try {
const { cart, total, address, date, telegramId, telegramUsername, telegramFirstName, type, phone } = req.body;
// Track user from order
if (telegramId) {
try {
await supabase.from('bot_users').upsert({
telegram_id: telegramId.toString(),
username: telegramUsername,
first_name: telegramFirstName,
phone: phone || null,
last_seen: new Date().toISOString()
}, { onConflict: 'telegram_id' });
} catch (e) {
console.warn('Could not track user from order:', e);
}
}
// Create order in database
const { data: order, error: orderError } = await supabase.from('orders').insert([{
client_telegram_id: telegramId?.toString(),
client_name: telegramFirstName || telegramUsername || phone || 'Inconnu',
total,
address,
items: cart,
type: type || 'delivery',
status: 'pending'
}]).select().single();
if (orderError) throw orderError;
// Fetch all drivers or meetup workers
const { data: drivers } = await supabase.from('drivers').select('*');
const { data: workers } = await supabase.from('meetup_workers').select('*');
// Try to fetch settings
let settings: any = null;
try {
const { data, error } = await supabase.from('shop_settings').select('*').eq('id', 1).single();
if (!error) settings = data;
} catch (e) {}
const managerChatId = settings?.manager_chat_id || adminId;
const managerUsername = (settings?.order_manager || process.env.VITE_ORDER_MANAGER_USERNAME || 'manager').replace('@', '');
const { query } = parseAddress(order.address || '');
const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
const appleMapsUrl = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
const wazeUrl = `https://waze.com/ul?q=${encodeURIComponent(query)}`;
const managerMessage = await constructOrderMessage(order.id, true);
const driverMessage = await constructOrderMessage(order.id, false);
const baseButtons: any[][] = [];
if (order.type !== 'meetup') {
baseButtons.push([
{ text: "🌐 GOOGLE MAPS", url: googleMapsUrl },
{ text: "🍎 APPLE MAPS", url: appleMapsUrl }
]);
baseButtons.push([{ text: "🚙 WAZE", url: wazeUrl }]);
}
// Send to manager and admin
const recipients = [
{ id: formatChatId(adminId), role: 'admin' },
{ id: formatChatId(settings?.manager_chat_id), role: 'manager' }
].filter(r => r.id);
// Filter unique IDs to avoid double sending if admin is also manager
const uniqueRecipients = recipients.filter((v, i, a) => a.findIndex(t => t.id === v.id) === i);
for (const recipient of uniqueRecipients) {
try {
const mgrMsg = await bot.telegram.sendMessage(recipient.id!, managerMessage, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: baseButtons
}
});
// Store notification to update later
await supabase.from('order_notifications').insert([{
order_id: order.id,
driver_id: recipient.role,
message_id: mgrMsg.message_id
}]);
} catch (mgrErr) {
console.error(`Failed to send notification to ${recipient.id}:`, mgrErr);
}
}
// Send to all drivers or meetup workers
const targets = order.type === 'meetup' ? workers : drivers;
const callbackData = order.type === 'meetup' ? `take_meetup_${order.id}` : `take_order_${order.id}`;
const buttonText = order.type === 'meetup' ? "🤝 PRENDRE LE MEET-UP" : "📦 PRENDRE LA COMMANDE";
const dispatchMode = settings?.order_dispatch_mode || 'private';
const deliveryGroupId = settings?.delivery_group_id;
const meetupGroupId = settings?.meetup_group_id;
if (dispatchMode === 'group') {
const targetGroupId = order.type === 'meetup' ? meetupGroupId : deliveryGroupId;
if (targetGroupId && !isNaN(Number(targetGroupId))) {
try {
const sentMsg = await bot.telegram.sendMessage(targetGroupId, driverMessage, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [...baseButtons, [{ text: buttonText, callback_data: callbackData }]]
}
});
// Store notification to update later
await supabase.from('order_notifications').insert([{
order_id: order.id,
driver_id: targetGroupId,
message_id: sentMsg.message_id
}]);
} catch (e) {
console.error(`Failed to send order to group ${targetGroupId}:`, e);
}
}
} else if (targets && targets.length > 0) {
for (const target of targets) {
try {
const sentMsg = await bot.telegram.sendMessage(target.telegram_id, driverMessage, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [...baseButtons, [{ text: buttonText, callback_data: callbackData }]]
}
});
// Store notification to update later
await supabase.from('order_notifications').insert([{
order_id: order.id,
driver_id: target.telegram_id,
message_id: sentMsg.message_id
}]);
} catch (e) {
console.error(`Failed to send order to target ${target.telegram_id}:`, e);
}
}
}
// Send confirmation to client
if (telegramId) {
try {
const clientMsg = order.type === 'meetup'
? `✅ <b>Commande confirmée !</b>\n\nVotre commande de <b>${total}€</b> a été transmise aux collaborateurs.\n\n📍 Point de RDV :\n<code>${escapeHTML(address)}</code>\n\nUn collaborateur va vous contacter sous peu pour fixer le point de rendez-vous précis.`
: `✅ <b>Commande confirmée !</b>\n\nVotre commande de <b>${total}€</b> a été transmise aux livreurs.\n\n📍 Livraison prévue à :\n<code>${escapeHTML(address)}</code>\n\nUn livreur va vous répondre sous peu, veuillez rester attentif.`;
await bot.telegram.sendMessage(telegramId, clientMsg, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: "💬 CONTACTER LE MANAGER", url: `https://t.me/${managerUsername}` }]
]
}
});
} catch (clientErr) {}
}
res.json({ success: true });
} catch (error: any) {
console.error('Order processing error:', error);
res.status(500).json({ error: "Failed to process order", details: error.message });
}
});
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
// --- LIKES ENDPOINT ---
app.post('/api/likes', async (req, res) => {
const { productId, userId, action } = req.body;
if (!productId || !userId) {
return res.status(400).json({ success: false, error: 'Missing parameters' });
}
try {
if (action === 'add') {
const { error } = await supabase
.from('product_likes')
.upsert({ product_id: productId, user_telegram_id: userId.toString() });
if (error) throw error;
} else if (action === 'remove') {
const { error } = await supabase
.from('product_likes')
.delete()
.eq('product_id', productId)
.eq('user_telegram_id', userId.toString());
if (error) throw error;
}
res.json({ success: true });
} catch (error: any) {
console.error('Likes API Error:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// --- CONFIGURATION WEBHOOK & DÉMARRAGE HUGGING FACE ---
// 1. On crée le chemin secret pour Telegram
const secretPath = `/telegraf/${botToken}`;
// 2. On dit à ton serveur Express d'écouter Telegram
app.use(bot.webhookCallback(secretPath));
// 3. On lance le serveur sur le port 7860
app.listen(7860, '0.0.0.0', async () => {
console.log(`🚀 Serveur opérationnel sur le port 7860`);
// 4. On enregistre l'URL du bot auprès de Telegram
if (appUrl) {
try {
await bot.telegram.deleteWebhook();
await bot.telegram.setWebhook(`${appUrl}${secretPath}`);
console.log(`✅ Webhook configuré : ${appUrl}${secretPath}`);
} catch (e: any) {
console.error("❌ Erreur configuration Webhook:", e.message);
}
} else {
console.error("⚠️ CUSTOM_APP_URL est vide dans tes Secrets HF !");
}
});
} // Cette accolade ferme ta fonction "async function startServer() {"
// On lance enfin toute la machine
startServer();
import express from 'express';
import { createServer as createViteServer } from 'vite';
import { Telegraf, Context, Scenes, session, Markup } from 'telegraf';
import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { HttpsProxyAgent } from 'https-proxy-agent';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const supabaseUrl = process.env.SUPABASE_URL || '';
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY || '';
if (!supabaseUrl || !supabaseServiceKey) {
console.error('CRITICAL: Supabase configuration is missing! Check SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY/SUPABASE_ANON_KEY');
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
const botToken = process.env.TELEGRAM_BOT_TOKEN || '';
const adminId = (process.env.ADMIN_TELEGRAM_ID || '').replace('@', '').trim();
// Helper to format chat ID for Telegram (adds @ to usernames)
const formatChatId = (id: string) => {
if (!id) return null;
const trimmed = id.trim();
if (!trimmed) return null;
// If it's a numeric ID (can be negative for groups)
if (/^-?\d+$/.test(trimmed)) return trimmed;
// If it's a username, ensure it starts with @
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
};
// Helper to check if a user is admin or manager
const isUserAdminOrManager = (userId: string | number, username: string | null, settings: any) => {
const uid = userId.toString().trim();
const uname = (username || '').replace('@', '').trim();
const cleanAdminId = adminId.replace('@', '').trim();
const cleanManagerId = (settings?.manager_chat_id || '').toString().replace('@', '').trim();
const isAdmin = (cleanAdminId && (uid === cleanAdminId || (uname && uname === cleanAdminId)));
const isManager = (cleanManagerId && (uid === cleanManagerId || (uname && uname === cleanManagerId)));
return { isAdmin, isManager, isEither: isAdmin || isManager };
};
// Use a custom URL if provided, otherwise fallback to SHARED_APP_URL or APP_URL
const appUrl = process.env.CUSTOM_APP_URL || process.env.SHARED_APP_URL || process.env.APP_URL || '';
console.log('Config Check:', {
hasBotToken: !!botToken,
adminId: adminId,
hasSupabaseUrl: !!supabaseUrl,
hasSupabaseKey: !!supabaseServiceKey,
isServiceKey: !!process.env.SUPABASE_SERVICE_ROLE_KEY,
appUrl: appUrl
}); // <--- C'est cette parenthèse qui manquait !
// --- MODIFICATION HUGGING FACE ---
const bot = new Telegraf(botToken);
let botUsername = 'Bot';
bot.telegram.getMe().then(me => {
botUsername = me.username;
console.log(`✅ Bot en ligne : @${botUsername}`);
}).catch(err => {
console.log('⚠️ Note: Connexion initiale Telegram impossible, attente du Webhook...');
});
// Set bot descriptions (visible before clicking Start)
const setBotDescriptions = async () => {
try {
const { data: settings } = await supabase.from('shop_settings').select('name, welcome_message').eq('id', 1).single();
const shopName = settings?.name || 'Shop';
// Use the custom welcome message if it exists, otherwise use a dynamic default
let description = settings?.welcome_message || `Salut tout le monde ! Bienvenue sur le bot officiel ${shopName} 🇫🇷 !\n\nClique sur COMMANDER pour voir le menu, et n'oublie pas d'aller faire un tour dans la partie info pour tout savoir avant de passer ta commande 😉 ✅`;
// Dynamic replacement of old names if they exist in the saved message
description = description.replace(/Luigi Shop|Ma Boutique/g, shopName);
const shortDescription = `Bot officiel ${shopName} 🇫🇷 - Commandez vos produits préférés en quelques clics !`;
await bot.telegram.setMyDescription(description);
await bot.telegram.setMyShortDescription(shortDescription);
// Set the global menu button to open the web app
if (appUrl) {
await bot.telegram.setChatMenuButton({
menuButton: {
type: 'web_app',
text: 'COMMANDER',
web_app: { url: appUrl }
}
});