import Notification from "../models/NotificationModel.js"; // ─── Templates ──────────────────────────────────────────────────────────────── // Keys must match InvoiceModel.restaurantStatus values exactly const WHATSAPP_TEMPLATES = { "order-confirmed": { ar: "✅ تم تأكيد طلبك رقم #{orderNumber} في {restaurantName}.\nسيتم تحضيره خلال {estimatedTime} دقيقة. شكراً لاختيارك!", }, "pending": { ar: "📋 تم استلام طلبك رقم #{orderNumber} في {restaurantName}.\nجاري المراجعة الآن.", }, "preparing": { ar: "👨‍🍳 طلبك رقم #{orderNumber} قيد التحضير الآن!\n\n🧾 الأصناف:\n{itemsList}", }, "ready_for_delivery": { ar: "🍽️ طلبك رقم #{orderNumber} جاهز للاستلام من {restaurantName}!", }, "dine-in-ready": { ar: "🔔 طلبك رقم #{orderNumber} جاهز على طاولتك في {restaurantName}!", }, "shipped": { ar: "🚚 طلبك رقم #{orderNumber} في الطريق إليك!\n\n🧾 الأصناف:\n{itemsList}\n\n💰 الإجمالي: {total}\n\n🏍️ السائق: {driverName}\n📞 هاتف السائق: {driverPhone}", }, "out_for_delivery": { ar: "🏎️ طلبك في الطريق إليك الآن!\nالسائق: {driverName} — رقم: {driverPhone}", }, "delivered": { ar: "✅ تم تسليم طلبك رقم #{orderNumber} بنجاح.\nشكراً لتعاملك مع {restaurantName} 🙏", }, }; // ─── Meta Cloud API Config ──────────────────────────────────────────────────── // Set these environment variables in your .env file: // // WHATSAPP_PHONE_NUMBER_ID= // WHATSAPP_ACCESS_TOKEN= // WHATSAPP_API_VERSION=v20.0 (optional, defaults to v20.0) // // Get credentials from: https://developers.facebook.com > WhatsApp Business > API Setup const META_PHONE_NUMBER_ID = process.env.WHATSAPP_PHONE_NUMBER_ID; const META_ACCESS_TOKEN = process.env.WHATSAPP_ACCESS_TOKEN; const META_API_VERSION = process.env.WHATSAPP_API_VERSION || "v20.0"; const META_API_URL = `https://graph.facebook.com/${META_API_VERSION}/${META_PHONE_NUMBER_ID}/messages`; // ─── Helper: normalize phone number to E.164 format ────────────────────────── // Examples: "01012345678" → "+201012345678" // "+20 101 234 5678" → "+201012345678" const normalizePhone = (phone, defaultCountryCode = "20") => { if (!phone) return null; // Remove all non-digit characters let digits = phone.replace(/\D/g, ""); // Egyptian numbers starting with 0: strip and prepend country code if (digits.startsWith("0") && digits.length === 11) { digits = defaultCountryCode + digits.slice(1); } // Already has country code without + if (digits.length >= 12) { return "+" + digits; } return "+" + defaultCountryCode + digits; }; class WhatsAppService { /** * Queue a WhatsApp notification in the database */ static async queueNotification({ tenant, invoice, customer, phoneNumber, notificationType, orderNumber, estimatedTime, deliveryNote, driverName, driverPhone, restaurantName, itemsList, total, language = "ar", }) { try { if (!tenant || !invoice || !phoneNumber || !notificationType) { console.error("[WhatsApp] Missing required params:", { tenant: !!tenant, invoice: !!invoice, phoneNumber: !!phoneNumber, notificationType, }); throw new Error("Missing required notification parameters"); } const template = WHATSAPP_TEMPLATES[notificationType]; if (!template) { console.error("[WhatsApp] Unknown type:", notificationType, "| Available:", Object.keys(WHATSAPP_TEMPLATES)); throw new Error(`Unknown notification type: ${notificationType}`); } // Build message let message = template[language] || template.ar; message = message .replace(/{orderNumber}/g, orderNumber || "") .replace(/{estimatedTime}/g, estimatedTime || "30") .replace(/{deliveryNote}/g, deliveryNote || "") .replace(/{driverName}/g, driverName || "—") .replace(/{driverPhone}/g, driverPhone || "—") .replace(/{restaurantName}/g, restaurantName || "") .replace(/{itemsList}/g, itemsList || "") .replace(/{total}/g, total || ""); const notification = new Notification({ tenant, invoice, customer: customer || null, phoneNumber, notificationType, messageTemplate: message, channel: "whatsapp", status: "queued", }); await notification.save(); // ✅ Attempt immediate send (non-blocking — failure just updates status to retry later) WhatsAppService.sendWhatsAppMessage(notification).catch((err) => { console.warn("[WhatsApp] Background send failed — will retry via queue:", err.message); }); return notification; } catch (error) { console.error("[WhatsApp] Queue error:", error.message); throw error; } } /** * Send pending queued messages (call via cron job or manual trigger) * ✅ Fixed: was using string "$maxRetries" — now uses $expr for field comparison */ static async sendQueuedNotifications() { try { const pendingNotifications = await Notification.find({ status: "queued", $expr: { $lt: ["$retryCount", "$maxRetries"] }, // ✅ correct field-to-field comparison }) .limit(10) .populate("order", "invoiceNumber") .populate("tenant", "name"); for (const n of pendingNotifications) { await WhatsAppService.sendWhatsAppMessage(n); } return { processed: pendingNotifications.length }; } catch (error) { console.error("[WhatsApp] Send queue error:", error.message); throw error; } } /** * ✅ Feature #5: Send a WhatsApp message via Meta Cloud API * Falls back to console log in dev mode (when credentials not set) */ static async sendWhatsAppMessage(notification) { try { const normalizedPhone = normalizePhone(notification.phoneNumber); if (!normalizedPhone) { throw new Error(`Invalid phone number: ${notification.phoneNumber}`); } if (!META_PHONE_NUMBER_ID || !META_ACCESS_TOKEN) { // Dev mode: log instead of sending console.log(`[WhatsApp DEV] Would send to ${normalizedPhone}:`); console.log(notification.messageTemplate); notification.status = "sent"; notification.sentAt = new Date(); notification.externalId = `dev-${Date.now()}`; await notification.save(); return notification; } // ✅ Meta Cloud API — send free-form text message const response = await fetch(META_API_URL, { method: "POST", headers: { "Authorization": `Bearer ${META_ACCESS_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", to: normalizedPhone, type: "text", text: { preview_url: false, body: notification.messageTemplate, }, }), }); const responseData = await response.json(); if (!response.ok) { throw new Error( responseData?.error?.message || `API error ${response.status}` ); } // Mark as sent notification.status = "sent"; notification.sentAt = new Date(); notification.externalId = responseData?.messages?.[0]?.id || null; await notification.save(); console.log(`[WhatsApp] ✅ Sent to ${normalizedPhone} [${notification.notificationType}]`); return notification; } catch (error) { console.error(`[WhatsApp] ❌ Send error for ${notification.phoneNumber}:`, error.message); notification.retryCount += 1; notification.errorMessage = error.message; if (notification.retryCount >= notification.maxRetries) { notification.status = "failed"; } await notification.save(); throw error; } } /** * Get notification history for a specific order */ static async getOrderNotifications(tenantId, orderId) { return await Notification.find({ invoice: invoiceId, order: orderId, }).sort({ createdAt: -1 }); } } export default WhatsAppService;