I looked all across FlutterFlow community docs and YouTube but found nothing specific. I learned a little about cloud functions in FireBase and used ChatGPT to make the following custom cloud function, but it isn't working.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code
exports.dailyUpdateMedicine = functions.https.onCall(
(data, context) => {
// Write your code below!
// This function runs every day at midnight UTC
exports.dailyActionCronJob = functions.pubsub.schedule('0 0 * * *').onRun(async (context) => {
const db = admin.firestore();
try {
// Step 1: Query the 'users' collection to get all users
const usersSnapshot = await db.collection('users').get();
if (usersSnapshot.empty) {
console.log('No users found');
return;
}
// Step 2: Loop through each user and process their documents
usersSnapshot.forEach(async (userDoc) => {
const userId = userDoc.id; // The UID of the current user
// Query the 'medicine' collection for the specific user
const medicineQuerySnapshot = await db.collection('medicine')
.where('medicine_createdBy', '==', db.doc(`users/${userId}`)) // Filter by the current user's UID
.get();
if (medicineQuerySnapshot.empty) {
console.log(`No medicine documents found for user: ${userId}`);
return;
}
// Step 3: Start a batch to write documents and updates
const batch = db.batch(); // Using a batch for atomic operations
medicineQuerySnapshot.forEach((doc) => {
const data = doc.data();
// Step 4: Create a corresponding document in 'medicineHistory'
const medicineHistoryRef = db.collection('medicineHistory').doc(); // Create a new document ID
batch.set(medicineHistoryRef, {
mH_name: data.medicine_name,
mH_dosageAmount: data.medicine_dosage_amount,
mH_dosageUnit: data.medicine_dosage_unit,
mH_description: data.medicine_description,
mH_createdBy: db.doc(`users/${userId}`), // Reference to the user
mH_wasCompleted: data.medicine_isCompleted,
mH_notes: data.medicine_notes,
mH_createdDate: admin.firestore.FieldValue.serverTimestamp(), // Timestamp of when the record is created
});
// Step 5: Update the corresponding 'medicine' document with reset values
const docRef = db.collection('medicine').doc(doc.id);
batch.update(docRef, {
medicine_timeIndex: 0,
medicine_isCompleted: false,
medicine_amountComplete: 0,
medicine_isIncompleted: false,
medicine_notes: '', // Clear the notes
});
});
// Step 6: Commit the batch (both set and update operations)
await batch.commit();
console.log(`Successfully processed documents for user: ${userId}`);
// Step 7: Delete documents in 'medicine' where 'medicine_isDaily' is false
const deleteQuerySnapshot = await db.collection('medicine')
.where('medicine_isDaily', '==', false) // Filter for documents where 'medicine_isDaily' is false
.where('medicine_createdBy', '==', db.doc(`users/${userId}`)) // Ensure the document belongs to the user
.get();
deleteQuerySnapshot.forEach((doc) => {
// Delete the document
db.collection('medicine').doc(doc.id).delete();
console.log(`Document with ID ${doc.id} deleted due to 'medicine_isDaily' being false`);
});
});
} catch (error) {
console.error('Error running medicine cron job:', error);
}
});
// Write your code above!
}
);