Batch Update Documents Daily

Actions & Logic

Hey,

I'm not new to flutterflow, but I have little actual coding experience. I'm creating a medical app and want to implement a feature for medicine tracking.

I've already developed the foundation for this feature: the app has a list of the user's added medicine with a check and 'x' button to allow a patient's caregiver to track if the patient took the medicine at the given time (you can add multiple times to one medicine). Each time the caregiver tracks the medicine, a progress bar progressively fills (or doesn't if the patient didn't take the medicine).

What I need to add is the following ability: at midnight every day, I want the progress of EACH medicine (which are documents) to be saved in a new document as a medicine record. So, every night, a new 'medicineRecord' document would be created for each 'medicine' document. The new medicineRecord document would carry over the name, times, etc., as well as if it was 'completed' or not.

Then, the original 'medicine' documents would reset their daily value to 0, which would reset the progress bar for the following day. Finally, I would want the daily notifications to carry over. I know how to create notifications when the person initially creates the 'medicine' document based on the times they add, but how would I make them occur daily at the same specified times?

Again, this function would run at midnight every day, even when the app isn't open and the user isn't active.

What have you tried so far?

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!

}

);

Did you check FlutterFlow's Documentation for this topic?
Yes
1
3 replies