Spaces:
Paused
Paused
Download src/utils/notifications.js from Huzaifa1313/prof002313: direct link, hf CLI and curl.
- Browser
- Download file 7.72 kB
-
https://huggingface.co/spaces/Huzaifa1313/prof002313/resolve/main/src/utils/notifications.js
- Command line
-
hf download hf://spaces/Huzaifa1313/prof002313/src/utils/notifications.js
-
curl -L -o notifications.js https://huggingface.co/spaces/Huzaifa1313/prof002313/resolve/main/src/utils/notifications.js
7.72 kB
| const { messaging } = require('../config/firebase'); | |
| const { dbGet, dbUpdate } = require('../config/firebase'); | |
| /** | |
| * Send notification to a single user | |
| * @param {string} userId - Firebase UID of the user | |
| * @param {string} title - Notification title | |
| * @param {string} body - Notification body | |
| * @param {object} data - Optional additional data | |
| * @returns {Promise<object>} Result object | |
| */ | |
| async function sendNotificationToUser(userId, title, body, data = {}) { | |
| try { | |
| // Get user's FCM token from database | |
| const userData = await dbGet(`users/${userId}`); | |
| const token = userData?.fcmToken; | |
| if (!token) { | |
| console.log(`β οΈ No FCM token found for user: ${userId}`); | |
| return { success: false, error: 'No token found' }; | |
| } | |
| // Prepare message | |
| const message = { | |
| notification: { | |
| title: title, | |
| body: body, | |
| }, | |
| data: data, | |
| token: token, | |
| android: { | |
| priority: 'high', | |
| notification: { | |
| sound: 'default', | |
| channelId: 'service_connect_channel', | |
| }, | |
| }, | |
| apns: { | |
| payload: { | |
| aps: { | |
| sound: 'default', | |
| }, | |
| }, | |
| }, | |
| }; | |
| // Send notification | |
| const response = await messaging.send(message); | |
| console.log(`β Notification sent to ${userId}: ${title}`); | |
| return { success: true, response: response }; | |
| } catch (error) { | |
| console.log(`β Failed to send notification to ${userId}:`, error.message); | |
| // If token is invalid, remove it | |
| if (error.code === 'messaging/invalid-registration-token' || | |
| error.code === 'messaging/registration-token-not-registered') { | |
| console.log(`ποΈ Removing invalid token for user: ${userId}`); | |
| await dbUpdate(`users/${userId}`, { fcmToken: null }); | |
| } | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| /** | |
| * Send notification to multiple users | |
| * @param {string[]} userIds - Array of Firebase UIDs | |
| * @param {string} title - Notification title | |
| * @param {string} body - Notification body | |
| * @param {object} data - Optional additional data | |
| * @returns {Promise<object>} Result object | |
| */ | |
| async function sendNotificationToMultipleUsers(userIds, title, body, data = {}) { | |
| try { | |
| const tokens = []; | |
| // Collect all valid tokens | |
| for (const userId of userIds) { | |
| const userData = await dbGet(`users/${userId}`); | |
| const token = userData?.fcmToken; | |
| if (token) { | |
| tokens.push(token); | |
| } | |
| } | |
| if (tokens.length === 0) { | |
| console.log('β οΈ No valid FCM tokens found for any user'); | |
| return { success: false, count: 0 }; | |
| } | |
| // Prepare multicast message | |
| const message = { | |
| notification: { | |
| title: title, | |
| body: body, | |
| }, | |
| data: data, | |
| tokens: tokens, | |
| android: { | |
| priority: 'high', | |
| }, | |
| }; | |
| // Send to all | |
| const response = await messaging.sendEachForMulticast(message); | |
| console.log(`β Notification sent to ${response.successCount} devices, failed: ${response.failureCount}`); | |
| return { | |
| success: true, | |
| successCount: response.successCount, | |
| failureCount: response.failureCount | |
| }; | |
| } catch (error) { | |
| console.log('β Multicast send failed:', error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| /** | |
| * Save FCM token for a user | |
| * @param {string} userId - Firebase UID | |
| * @param {string} token - FCM device token | |
| * @returns {Promise<object>} Result object | |
| */ | |
| async function saveFcmToken(userId, token) { | |
| try { | |
| if (!userId || !token) { | |
| return { success: false, error: 'userId and token required' }; | |
| } | |
| await dbUpdate(`users/${userId}`, { | |
| fcmToken: token, | |
| fcmTokenUpdatedAt: Date.now() | |
| }); | |
| console.log(`β FCM token saved for user: ${userId}`); | |
| return { success: true }; | |
| } catch (error) { | |
| console.log(`β Failed to save FCM token:`, error.message); | |
| return { success: false, error: error.message }; | |
| } | |
| } | |
| /** | |
| * Send booking notification to professional | |
| * @param {string} professionalId - Professional's UID | |
| * @param {string} customerName - Customer's name | |
| * @param {string} bookingId - Booking ID | |
| */ | |
| async function sendNewBookingNotification(professionalId, customerName, bookingId) { | |
| const title = 'π New Booking Request!'; | |
| const body = `${customerName} has requested your service. Tap to view details.`; | |
| const data = { | |
| type: 'new_booking', | |
| bookingId: bookingId, | |
| timestamp: Date.now().toString(), | |
| }; | |
| return await sendNotificationToUser(professionalId, title, body, data); | |
| } | |
| /** | |
| * Send price offer notification to customer | |
| * @param {string} customerId - Customer's UID | |
| * @param {string} professionalName - Professional's name | |
| * @param {number} price - Offered price | |
| * @param {string} bookingId - Booking ID | |
| */ | |
| async function sendPriceOfferNotification(customerId, professionalName, price, bookingId) { | |
| const title = 'π° Price Offer Received'; | |
| const body = `${professionalName} offered Rs. ${price} for your service request.`; | |
| const data = { | |
| type: 'price_offer', | |
| bookingId: bookingId, | |
| price: price.toString(), | |
| }; | |
| return await sendNotificationToUser(customerId, title, body, data); | |
| } | |
| /** | |
| * Send booking accepted notification to customer | |
| * @param {string} customerId - Customer's UID | |
| * @param {string} professionalName - Professional's name | |
| * @param {string} bookingId - Booking ID | |
| */ | |
| async function sendBookingAcceptedNotification(customerId, professionalName, bookingId) { | |
| const title = 'β Booking Accepted!'; | |
| const body = `${professionalName} has accepted your booking. Contact details are now available.`; | |
| const data = { | |
| type: 'booking_accepted', | |
| bookingId: bookingId, | |
| }; | |
| return await sendNotificationToUser(customerId, title, body, data); | |
| } | |
| /** | |
| * Send job completion notification to professional | |
| * @param {string} professionalId - Professional's UID | |
| * @param {string} customerName - Customer's name | |
| * @param {string} bookingId - Booking ID | |
| */ | |
| async function sendJobCompletedByCustomerNotification(professionalId, customerName, bookingId) { | |
| const title = 'β Customer Confirmed Completion'; | |
| const body = `${customerName} has confirmed that the job is complete. Tap to mark as done.`; | |
| const data = { | |
| type: 'customer_completed', | |
| bookingId: bookingId, | |
| }; | |
| return await sendNotificationToUser(professionalId, title, body, data); | |
| } | |
| /** | |
| * Send notification to nearby professionals for new service post | |
| * @param {string[]} professionalIds - Array of professional UIDs nearby | |
| * @param {string} customerName - Customer's name | |
| * @param {string} description - Service description | |
| * @param {string} postId - Post ID | |
| */ | |
| async function sendNewServicePostNotification(professionalIds, customerName, description, postId) { | |
| const title = 'π New Service Request Near You!'; | |
| const shortDesc = description.length > 50 ? description.substring(0, 50) + '...' : description; | |
| const body = `${customerName} needs: ${shortDesc}`; | |
| const data = { | |
| type: 'new_service_post', | |
| postId: postId, | |
| }; | |
| if (professionalIds.length === 1) { | |
| return await sendNotificationToUser(professionalIds[0], title, body, data); | |
| } else { | |
| return await sendNotificationToMultipleUsers(professionalIds, title, body, data); | |
| } | |
| } | |
| module.exports = { | |
| // Core functions | |
| sendNotificationToUser, | |
| sendNotificationToMultipleUsers, | |
| saveFcmToken, | |
| // Convenience functions for booking flow | |
| sendNewBookingNotification, | |
| sendPriceOfferNotification, | |
| sendBookingAcceptedNotification, | |
| sendJobCompletedByCustomerNotification, | |
| sendNewServicePostNotification, | |
| }; |