Prof_app / src /utils /notifications.js
Huzaifa1435's picture
Initial Commit: Clean backend without large files
e3fefe8
Raw History Blame Contribute Delete
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,
};