MultiUsersSalesSystem / utils /whatsappService.js
Mahmoud7456's picture
Upload 72 files
0330133 verified
Raw History Blame Contribute Delete
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;