Spaces:
Sleeping
Sleeping
File size: 9,181 Bytes
0330133 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | 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;
|