Hi everyone, I'm working on a FlutterFlow app that has a 'MaintenanceLog' collection. Each document in this collection has a 'NextRepairDate1' field (formatted as a Date/DateTime). I'm struggling to figure out the best way to trigger notifications when the 'NextRepairDate1' matches the current date. my FCM tokens are stored in 'Users' collection.
I'd like my app to automatically send a notification to all the users (only 5-10 users) when a 'MaintenanceLog' item's 'NextRepairDate1' matches today's date.
Push Notifications with Google Cloud Functions
I deployed a cloud function and it was successful. but its not triggering the notification when i test run it. here is the code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.sendMaintenanceNotifications = functions.pubsub.schedule('every day 00:00').onRun((context) => {
const today = new Date().toLocaleDateString();
const notificationRef = admin.firestore().collection('MaintenanceLog')
.where('NextRepairDate1', '==', today);
return notificationRef.get()
.then(maintenanceLogSnapshot => {
const promises = [];
maintenanceLogSnapshot.forEach(maintenanceDoc => {
const userId = maintenanceDoc.data().userId;
// Fetch most recent FCM token
const userFcmTokenRef = admin.firestore().collection('Users')
.doc(userId).collection('fcm_token')
.orderBy('created_at', 'desc').limit(1);
return userFcmTokenRef.get()
.then(fcmTokenSnapshot => {
fcmTokenSnapshot.forEach(tokenDoc => {
const userDeviceToken = tokenDoc.data().fcm_token;
// Customize your notification message here
const notificationTitle = 'Maintenance Reminder';
const notificationBody = 'An item in your MaintenanceLog needs attention!';
const message = {
notification: {
title: notificationTitle,
body: notificationBody
},
token: userDeviceToken
};
promises.push(admin.messaging().send(message));
});
return Promise.all(promises);
});
});
})
.catch(error => {
console.error("Error sending notifications:", error);
});
});