Add notification

This commit is contained in:
Van Leemput Dayron
2025-11-28 19:16:37 +01:00
parent 0668fcad57
commit 68f546d0e8
9 changed files with 4638 additions and 14 deletions

125
functions/index.js Normal file
View File

@@ -0,0 +1,125 @@
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// Helper function to send notifications
async function sendNotificationToTripParticipants(tripId, title, body, excludeUserId) {
try {
const tripDoc = await admin.firestore().collection("trips").doc(tripId).get();
if (!tripDoc.exists) {
console.log(`Trip ${tripId} not found`);
return;
}
const trip = tripDoc.data();
const participants = trip.participants || [];
// Add creator if not in participants list (though usually they are)
if (trip.createdBy && !participants.includes(trip.createdBy)) {
participants.push(trip.createdBy);
}
const tokens = [];
for (const userId of participants) {
if (userId === excludeUserId) continue;
const userDoc = await admin.firestore().collection("users").doc(userId).get();
if (userDoc.exists) {
const userData = userDoc.data();
if (userData.fcmToken) {
tokens.push(userData.fcmToken);
}
}
}
if (tokens.length > 0) {
const message = {
notification: {
title: title,
body: body,
},
tokens: tokens,
data: {
tripId: tripId,
click_action: "FLUTTER_NOTIFICATION_CLICK",
},
};
const response = await admin.messaging().sendMulticast(message);
console.log(`${response.successCount} messages were sent successfully`);
}
} catch (error) {
console.error("Error sending notification:", error);
}
}
exports.onActivityCreated = functions.firestore
.document("trips/{tripId}/activities/{activityId}")
.onCreate(async (snapshot, context) => {
const activity = snapshot.data();
const tripId = context.params.tripId;
const createdBy = activity.createdBy || "Unknown"; // Assuming createdBy field exists
// Fetch creator name if possible, otherwise use generic message
let creatorName = "Quelqu'un";
if (createdBy !== "Unknown") {
const userDoc = await admin.firestore().collection("users").doc(createdBy).get();
if (userDoc.exists) {
creatorName = userDoc.data().prenom || "Quelqu'un";
}
}
await sendNotificationToTripParticipants(
tripId,
"Nouvelle activité !",
`${creatorName} a ajouté une nouvelle activité : ${activity.title}`,
createdBy
);
});
exports.onMessageCreated = functions.firestore
.document("trips/{tripId}/messages/{messageId}")
.onCreate(async (snapshot, context) => {
const message = snapshot.data();
const tripId = context.params.tripId;
const senderId = message.senderId;
let senderName = "Quelqu'un";
if (senderId) {
const userDoc = await admin.firestore().collection("users").doc(senderId).get();
if (userDoc.exists) {
senderName = userDoc.data().prenom || "Quelqu'un";
}
}
await sendNotificationToTripParticipants(
tripId,
"Nouveau message",
`${senderName} : ${message.content}`,
senderId
);
});
exports.onExpenseCreated = functions.firestore
.document("trips/{tripId}/expenses/{expenseId}")
.onCreate(async (snapshot, context) => {
const expense = snapshot.data();
const tripId = context.params.tripId;
const paidBy = expense.paidBy;
let payerName = "Quelqu'un";
if (paidBy) {
const userDoc = await admin.firestore().collection("users").doc(paidBy).get();
if (userDoc.exists) {
payerName = userDoc.data().prenom || "Quelqu'un";
}
}
await sendNotificationToTripParticipants(
tripId,
"Nouvelle dépense",
`${payerName} a ajouté une dépense : ${expense.amount} ${expense.currency || '€'}`,
paidBy
);
});

4284
functions/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

25
functions/package.json Normal file
View File

@@ -0,0 +1,25 @@
{
"name": "functions",
"description": "Cloud Functions for Travel Mate",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "18"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^11.8.0",
"firebase-functions": "^4.3.1"
},
"devDependencies": {
"eslint": "^8.15.0",
"eslint-config-google": "^0.14.0"
},
"private": true
}