Spaces:
Sleeping
Sleeping
Download utils/whatsappService.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 9.18 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/utils/whatsappService.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem/utils/whatsappService.js
-
curl -L -o whatsappService.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/utils/whatsappService.js
9.18 kB
| 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=<your Meta phone number ID> | |
| // WHATSAPP_ACCESS_TOKEN=<your Meta Graph API 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; | |