-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifications.js
More file actions
420 lines (356 loc) · 13.3 KB
/
Copy pathnotifications.js
File metadata and controls
420 lines (356 loc) · 13.3 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// notifications.js — Enhanced Payment & SMS Notifications
import { CONFIG } from './config.js';
export const NOTIFICATION_TEMPLATES = CONFIG.EMAILJS?.TEMPLATES || {
clientNew: 'template_client_new',
providerNew: 'template_provider_new',
reminder: 'template_reminder',
confirmation: 'template_confirmation'
};
// ==================== BROWSER NOTIFICATIONS ====================
export async function requestNotificationPermission() {
if (!('Notification' in window)) return false;
if (Notification.permission === 'granted') return true;
if (Notification.permission === 'denied') return false;
const permission = await Notification.requestPermission();
return permission === 'granted';
}
export function showBrowserNotification(title, options = {}) {
if (!('Notification' in window) || Notification.permission !== 'granted') return;
return new Notification(title, {
icon: '/icon.svg',
badge: '/icon.svg',
vibrate: [200, 100, 200],
...options
});
}
export function scheduleAppointmentReminder(appointment, minutesBefore = 60) {
const aptTime = new Date(`${appointment.date}T${appointment.time}`).getTime();
const reminderTime = aptTime - (minutesBefore * 60 * 1000);
const now = Date.now();
if (reminderTime > now) {
setTimeout(() => {
showBrowserNotification('تذكير بموعدك', {
body: `موعد ${appointment.clientName} في ${appointment.service} خلال ${minutesBefore >= 60 ? Math.floor(minutesBefore/60) + ' ساعة' : minutesBefore + ' دقيقة'}`,
tag: appointment.id
});
}, reminderTime - now);
}
}
export function scheduleMultiReminder(appointment, settings) {
const { waReminder, browserNotify } = settings;
// Schedule WhatsApp reminder
if (waReminder > 0) {
scheduleWhatsAppReminder(appointment, waReminder);
}
// Schedule browser notification
if (browserNotify > 0) {
scheduleAppointmentReminder(appointment, browserNotify);
}
}
function scheduleWhatsAppReminder(appointment, minutesBefore) {
const aptTime = new Date(`${appointment.date}T${appointment.time}`).getTime();
const reminderTime = aptTime - (minutesBefore * 60 * 1000);
const now = Date.now();
if (reminderTime > now) {
setTimeout(() => {
openWhatsAppNotify(appointment, 'reminder');
}, reminderTime - now);
}
}
/**
* Sends an email using EmailJS
*/
export async function sendEmailNotification(templateId, templateParams) {
try {
if (!window.emailjs) {
console.warn("EmailJS not loaded");
return;
}
// Auto-init with config key if not already done
if (CONFIG.EMAILJS.PUBLIC_KEY && CONFIG.EMAILJS.PUBLIC_KEY !== 'YOUR_EMAILJS_PUBLIC_KEY') {
emailjs.init({ publicKey: CONFIG.EMAILJS.PUBLIC_KEY });
}
const response = await emailjs.send(
CONFIG.EMAILJS.SERVICE_ID,
templateId,
templateParams
);
console.log('✅ Email Sent successfully:', response.status, response.text);
return response;
} catch (error) {
console.error('❌ Failed to send email:', error);
throw error;
}
}
/**
* Prepares a WhatsApp message for the provider to send to the client
*/
export function openWhatsAppNotify(appointment, type = 'confirm') {
const phone = (appointment.clientPhone || '').replace(/[^0-9]/g, '');
const fullPhone = phone.startsWith('0') ? '2' + phone : phone;
const messages = {
confirm: `مرحباً ${appointment.clientName}! 😊
بتم تأكيد حجزك في BookFlow:
📍 الخدمة: ${appointment.service || ''}
📅 التاريخ: ${appointment.dateStr || ''}
⏰ الوقت: ${appointment.time || ''}
شكراً لاختيارك! ✨`,
reminder: `تذكير بموعدك! ⏰
مرحباً ${appointment.clientName}!
📍 الخدمة: ${appointment.service || ''}
📅 التاريخ: ${appointment.dateStr || ''}
⏰ الوقت: ${appointment.time || ''}
لو محتاج أي مساعدة، رد علينا! 🔔`,
cancel: `مرحباً ${appointment.clientName}! 😔
تم إلغاء موعدك:
📍 الخدمة: ${appointment.service || ''}
📅 التاريخ: ${appointment.dateStr || ''}
⏰ الوقت: ${appointment.time || ''}
لو محتاج أي مساعدة، رد علينا! 🔔`,
custom: `مرحباً ${appointment.clientName}! 👋`
};
const message = encodeURIComponent(messages[type] || messages.custom);
window.open(`https://wa.me/${fullPhone}?text=${message}`, '_blank');
}
// ==================== PAYMENT GATEWAYS ====================
/**
* Initialize Stripe payment
*/
export function initStripe(publishableKey) {
return new Promise((resolve, reject) => {
if (window.Stripe) {
resolve(window.Stripe(publishableKey));
return;
}
const script = document.createElement('script');
script.src = 'https://js.stripe.com/v3/';
script.onload = () => resolve(window.Stripe(publishableKey));
script.onerror = reject;
document.head.appendChild(script);
});
}
/**
* Process payment with Stripe
*/
export async function processStripePayment(amount, description, metadata = {}) {
try {
const stripe = await initStripe(CONFIG.STRIPE.PUBLISHABLE_KEY);
if (!stripe) throw new Error('Stripe not initialized');
// Create payment intent on backend (mock for now)
const response = await fetch('/api/create-payment-intent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: Math.round(amount * 100), // Stripe expects cents
currency: 'egp',
description,
metadata
})
});
const { clientSecret } = await response.json();
// Confirm payment with Stripe
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret);
if (error) {
throw error;
}
console.log('✅ Payment successful:', paymentIntent);
return paymentIntent;
} catch (e) {
console.error('❌ Payment error:', e);
throw e;
}
}
/**
* Process payment with Vodafone Cash (mock)
*/
export async function processVodafoneCashPayment(phoneNumber, amount, reference = '') {
try {
// Mock implementation - in real scenario, call your backend
const response = await fetch('/api/vodafone-cash', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone: phoneNumber,
amount,
reference,
merchantCode: CONFIG.PAYMENT?.VODAFONE_CASH_CODE || 'YOUR_MERCHANT_CODE'
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Payment failed');
}
console.log('✅ Vodafone Cash payment initiated:', data);
return data;
} catch (e) {
console.error('❌ Vodafone Cash error:', e);
throw e;
}
}
/**
* Process payment with Paymob (mock)
*/
export async function processPaymobPayment(amount, description, billingData = {}) {
try {
// Mock implementation - in real scenario, call your backend
const response = await fetch('/api/paymob', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: Math.round(amount * 100), // Paymob expects cents
currency: 'EGP',
description,
billingData,
apiKey: CONFIG.PAYMENT?.PAYMOB_API_KEY || 'YOUR_PAYMOB_API_KEY'
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Payment failed');
}
// Redirect to Paymob payment page if needed
if (data.redirectUrl) {
window.location.href = data.redirectUrl;
return;
}
console.log('✅ Paymob payment initiated:', data);
return data;
} catch (e) {
console.error('❌ Paymob error:', e);
throw e;
}
}
// ==================== SMS NOTIFICATIONS ====================
/**
* Send SMS via Twilio (mock)
*/
export async function sendSMSNotification(phoneNumber, message) {
try {
// Mock implementation - in real scenario, call your backend
const response = await fetch('/api/sms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
to: phoneNumber,
message,
accountSid: CONFIG.SMS?.TWILIO_ACCOUNT_SID || 'YOUR_TWILIO_SID',
authToken: CONFIG.SMS?.TWILIO_AUTH_TOKEN || 'YOUR_TWILIO_TOKEN'
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'SMS failed');
}
console.log('✅ SMS sent successfully:', data);
return data;
} catch (e) {
console.error('❌ SMS error:', e);
throw e;
}
}
/**
* Send appointment confirmation SMS
*/
export async function sendAppointmentSMS(appointment) {
const phone = (appointment.clientPhone || '').replace(/[^0-9]/g, '');
const message = `مرحباً ${appointment.clientName}! تم تأكيد حجزك.
📍 ${appointment.service || ''}
📅 ${appointment.date || ''}
⏰ ${appointment.time || ''}
شكراً!`;
return sendSMSNotification(phone, message);
}
/**
* Send appointment reminder SMS
*/
export async function sendReminderSMS(appointment) {
const phone = (appointment.clientPhone || '').replace(/[^0-9]/g, '');
const message = `تذكير: موعدك ${appointment.service || ''} اليوم الساعة ${appointment.time || ''}.
شكراً!`;
return sendSMSNotification(phone, message);
}
// ==================== PAYMENT UI HELPERS ====================
/**
* Show payment modal
*/
export function showPaymentModal(appointment, onSuccess, onError) {
const modal = document.createElement('div');
modal.className = 'modal-overlay open';
modal.innerHTML = `
<div class="modal-box" style="max-width: 500px;">
<button class="modal-close" onclick="this.closest('.modal-overlay').remove()">
<i class="ph-bold ph-x"></i>
</button>
<h2 style="margin-bottom: 24px;">إتمام الدفع</h2>
<div style="background: var(--bg-surface); padding: 24px; border-radius: var(--radius-md); margin-bottom: 24px;">
<div style="display: flex; justify-content: space-between; margin-bottom: 16px;">
<span style="color: var(--text-secondary);">الخدمة:</span>
<strong>${appointment.service || ''}</strong>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 16px;">
<span style="color: var(--text-secondary);">المبلغ:</span>
<strong style="font-size: 1.3rem; color: var(--accent);">${appointment.price || 0} ج.م</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--text-secondary);">العميل:</span>
<span>${appointment.clientName || ''}</span>
</div>
</div>
<div style="display: flex; flex-direction: column; gap: 12px;">
<button class="btn-primary" onclick="window.processPayment('stripe', this)" style="width: 100%;">
<i class="ph-bold ph-credit-card"></i> دفع بالكارت (Stripe)
</button>
<button class="btn-secondary" onclick="window.processPayment('vodafone', this)" style="width: 100%;">
<i class="ph-bold ph-phone"></i> فودافون كاش
</button>
<button class="btn-secondary" onclick="window.processPayment('paymob', this)" style="width: 100%;">
<i class="ph-bold ph-money"></i> Paymob
</button>
</div>
</div>
`;
document.body.appendChild(modal);
document.body.style.overflow = 'hidden';
// Close on overlay click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
modal.remove();
document.body.style.overflow = '';
}
});
// Make payment processor available globally
window.processPayment = async (method, btn) => {
btn.disabled = true;
btn.innerHTML = '<i class="ph ph-circle-notch ph-spin"></i> جاري المعالجة...';
try {
if (method === 'stripe') {
await processStripePayment(appointment.price, appointment.service, {
appointmentId: appointment.id,
clientName: appointment.clientName
});
} else if (method === 'vodafone') {
await processVodafoneCashPayment(appointment.clientPhone, appointment.price, appointment.id);
} else if (method === 'paymob') {
await processPaymobPayment(appointment.price, appointment.service, {
first_name: appointment.clientName?.split(' ')[0] || '',
last_name: appointment.clientName?.split(' ').slice(1).join(' ') || '',
phone_number: appointment.clientPhone
});
}
showToast('تم الدفع بنجاح! ✅', 'success');
modal.remove();
document.body.style.overflow = '';
if (onSuccess) onSuccess();
} catch (e) {
console.error('Payment error:', e);
showToast('فشل الدفع: ' + e.message, 'error');
btn.disabled = false;
btn.innerHTML = `
<i class="ph-bold ph-${method === 'stripe' ? 'credit-card' : method === 'vodafone' ? 'phone' : 'money'}"></i>
${method === 'stripe' ? 'دفع بالكارت (Stripe)' : method === 'vodafone' ? 'فودافون كاش' : 'Paymob'}
`;
if (onError) onError(e);
}
};
}
console.log('✅ Notifications module loaded with Payment & SMS support');