Calendar, syncing rework

This commit is contained in:
Milan Paunovic
2024-11-27 01:37:58 +01:00
parent f2af60111b
commit 95d5e74703
9 changed files with 629 additions and 174 deletions

View File

@ -23,10 +23,32 @@ async function getPushTokensForFamily(familyId, excludeUserId = null) {
const snapshot = await usersRef.where('familyId', '==', familyId).get();
let pushTokens = [];
console.log('Getting push tokens:', {
familyId,
excludeUserId
});
snapshot.forEach(doc => {
const data = doc.data();
if ((!excludeUserId || data.uid !== excludeUserId) && data.pushToken) {
const userId = doc.id;
console.log('Processing user:', {
docId: userId,
hasToken: !!data.pushToken,
excluded: userId === excludeUserId
});
if (userId !== excludeUserId && data.pushToken) {
console.log('Including token for user:', {
userId,
excludeUserId
});
pushTokens.push(data.pushToken);
} else {
console.log('Excluding token for user:', {
userId,
excludeUserId
});
}
});
@ -194,6 +216,7 @@ exports.sendNotificationOnEventCreation = functions.firestore
const creatorId = eventData.creatorId;
const title = eventData.title || '';
const externalOrigin = eventData.externalOrigin || false;
const eventId = context.params.eventId;
if (!familyId || !creatorId) {
console.error('Missing familyId or creatorId in event data');
@ -214,9 +237,9 @@ exports.sendNotificationOnEventCreation = functions.firestore
creatorId,
externalOrigin: externalOrigin || false,
events: [{
id: context.params.eventId,
id: eventId,
title: title || '',
timestamp: new Date().toISOString()
timestamp: new Date().toISOString() // Using ISO string instead of serverTimestamp
}],
createdAt: admin.firestore.FieldValue.serverTimestamp(),
processed: false,
@ -226,19 +249,50 @@ exports.sendNotificationOnEventCreation = functions.firestore
const existingEvents = batchDoc.data().events || [];
transaction.update(batchRef, {
events: [...existingEvents, {
id: context.params.eventId,
id: eventId,
title: title || '',
timestamp: new Date().toISOString()
timestamp: new Date().toISOString() // Using ISO string instead of serverTimestamp
}]
});
}
});
console.log(`[HOUSEHOLD_UPDATE] Event created - Processing timestamp updates`, {
eventId,
familyId,
eventTitle: title || 'Untitled'
});
const householdsSnapshot = await admin.firestore().collection('Households')
.where('familyId', '==', familyId)
.get();
console.log(`[HOUSEHOLD_UPDATE] Found ${householdsSnapshot.size} households to update for family ${familyId}`);
const householdBatch = admin.firestore().batch();
householdsSnapshot.docs.forEach((doc) => {
console.log(`[HOUSEHOLD_UPDATE] Adding household ${doc.id} to update batch`);
householdBatch.update(doc.ref, {
lastSyncTimestamp: admin.firestore.FieldValue.serverTimestamp()
});
});
const batchStartTime = Date.now();
await householdBatch.commit();
console.log(`[HOUSEHOLD_UPDATE] Batch update completed in ${Date.now() - batchStartTime}ms`, {
familyId,
householdsUpdated: householdsSnapshot.size,
eventId
});
} catch (error) {
console.error('Error adding to event batch:', error);
console.error('Error in event creation handler:', error);
throw error;
}
});
exports.processEventBatches = functions.pubsub
.schedule('every 1 minutes')
.onRun(async (context) => {
@ -256,13 +310,27 @@ exports.processEventBatches = functions.pubsub
const batchData = doc.data();
const {familyId, creatorId, externalOrigin, events} = batchData;
console.log('Processing batch:', {
batchId: doc.id,
creatorId,
familyId
});
try {
const pushTokens = await getPushTokensForFamily(
familyId,
creatorId
);
// Add logging to see what tokens are returned
console.log('Push tokens retrieved:', {
batchId: doc.id,
tokenCount: pushTokens.length,
tokens: pushTokens
});
if (pushTokens.length) {
let notificationMessage;
if (externalOrigin) {
notificationMessage = `Calendar sync completed: ${events.length} ${events.length === 1 ? 'event has' : 'events have'} been added.`;
@ -1654,53 +1722,6 @@ exports.triggerMicrosoftSync = functions.https.onCall(async (data, context) => {
}
});
exports.updateHouseholdTimestampOnEventCreate = functions.firestore
.document('Events/{eventId}')
.onCreate(async (snapshot, context) => {
const eventData = snapshot.data();
const familyId = eventData.familyId;
const eventId = context.params.eventId;
console.log(`[HOUSEHOLD_UPDATE] Event created - Processing timestamp updates`, {
eventId,
familyId,
eventTitle: eventData.title || 'Untitled'
});
try {
const householdsSnapshot = await db.collection('Households')
.where('familyId', '==', familyId)
.get();
console.log(`[HOUSEHOLD_UPDATE] Found ${householdsSnapshot.size} households to update for family ${familyId}`);
const batch = db.batch();
householdsSnapshot.docs.forEach((doc) => {
console.log(`[HOUSEHOLD_UPDATE] Adding household ${doc.id} to update batch`);
batch.update(doc.ref, {
lastUpdateTimestamp: admin.firestore.FieldValue.serverTimestamp()
});
});
const batchStartTime = Date.now();
await batch.commit();
console.log(`[HOUSEHOLD_UPDATE] Batch update completed in ${Date.now() - batchStartTime}ms`, {
familyId,
householdsUpdated: householdsSnapshot.size,
eventId
});
} catch (error) {
console.error(`[HOUSEHOLD_UPDATE] Error updating households for event creation`, {
eventId,
familyId,
error: error.message,
stack: error.stack
});
throw error;
}
});
exports.updateHouseholdTimestampOnEventUpdate = functions.firestore
.document('Events/{eventId}')
.onUpdate(async (change, context) => {
@ -1725,7 +1746,7 @@ exports.updateHouseholdTimestampOnEventUpdate = functions.firestore
householdsSnapshot.docs.forEach((doc) => {
console.log(`[HOUSEHOLD_UPDATE] Adding household ${doc.id} to update batch`);
batch.update(doc.ref, {
lastUpdateTimestamp: admin.firestore.FieldValue.serverTimestamp()
lastSyncTimestamp: admin.firestore.FieldValue.serverTimestamp()
});
});