From 3d15d7bb747b9c1567faa7298dec7f446bf33594 Mon Sep 17 00:00:00 2001 From: Milan Paunovic Date: Fri, 7 Feb 2025 14:12:23 +0100 Subject: [PATCH] Functions update --- firebase/functions/index.js | 73 +++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/firebase/functions/index.js b/firebase/functions/index.js index 52fb930..d952124 100644 --- a/firebase/functions/index.js +++ b/firebase/functions/index.js @@ -1297,4 +1297,77 @@ exports.migrateEventNotifications = functions.https.onRequest(async (req, res) = timestamp: new Date().toISOString() }); } +}); + +exports.sendSyncNotification = functions.https.onRequest(async (req, res) => { + const userId = req.query.userId; + + if (!userId) { + console.error('[SYNC] Missing userId in request'); + return res.status(400).send('Missing userId'); + } + + try { + const userDoc = await db.collection("Profiles").doc(userId).get(); + if (!userDoc.exists) { + console.error(`[SYNC] No profile found for user ${userId}`); + return res.status(404).send("User profile not found"); + } + + const userData = userDoc.data(); + const googleAccounts = userData.googleAccounts || {}; + + // Get first Google account + const [email] = Object.keys(googleAccounts); + if (!email) { + console.error(`[SYNC] No Google account found for user ${userId}`); + return res.status(400).send("No Google account found"); + } + + const accountData = googleAccounts[email]; + const { accessToken, refreshToken } = accountData; + + if (!accessToken) { + console.error(`[SYNC] No access token for user ${userId}`); + return res.status(400).send("No access token found"); + } + + const familyId = userData.familyId; + if (!familyId) { + console.error(`[SYNC] No family ID for user ${userId}`); + return res.status(400).send("No family ID found"); + } + + console.log(`[SYNC] Starting calendar sync for user ${userId}`); + const syncStartTime = Date.now(); + + // Trigger immediate sync + await fetchAndSaveGoogleEvents({ + token: accessToken, + refreshToken, + email, + familyId, + creatorId: userId + }); + + // Update household timestamps + const householdsSnapshot = await db.collection('Households') + .where("familyId", "==", familyId) + .get(); + + const batch = db.batch(); + householdsSnapshot.docs.forEach((doc) => { + batch.update(doc.ref, { + lastSyncTimestamp: admin.firestore.FieldValue.serverTimestamp() + }); + }); + + await batch.commit(); + + console.log(`[SYNC] Completed sync for user ${userId} in ${Date.now() - syncStartTime}ms`); + res.status(200).send("Sync completed successfully"); + } catch (error) { + console.error(`[SYNC] Error in sync notification:`, error); + res.status(500).send("Sync failed"); + } }); \ No newline at end of file