Eloka Ogbonnia
ย ยทย One Man Army

Creating and deploying a scheduling/recurring Cloud Function

Database & APIs

I deployed a cloud function using flutterflow but it fails to run daily as scheduled. It doesn't create any Job on Cloud Scheduler console. Please find my current code below. It doesn't even deploy on Flutterflow but the cloud function gets added to firebase somehow.

Graham Herdman Please can you help, I saw that you have some experience with this.
Serge Middendorf

What have you tried so far?
const functions = require('firebase-functions');
const admin = require('firebase-admin');

// To avoid deployment errors, do not call admin.initializeApp() in your code

exports.dailyBenefit = functions.region('europe-central2')
  .runWith({
    memory: '256MB'
  })
  .pubsub.schedule('every day 00:00')
  .timeZone('Europe/Central')
  .onRun(async (context) => {
    // Write your code below!

    const ahorrosRef = admin.firestore().collection('ahorros');

    try {
      const querySnapshot = await ahorrosRef.get();

      const batch = admin.firestore().batch();

      querySnapshot.forEach(doc => {
        const docData = doc.data();
        const totalSavingValue = docData.TotalSavingValue || 0;
        const eaValue = (docData.EA/100) || 0;

        // Calculate the daily benefit
        const benefit = (totalSavingValue * eaValue) / 365;

        // Calculate the fullBenefit, taxedBenefit, and tax
        //const fullBenefit = benefit;
        const taxedBenefit = benefit * 0.93;
        const tax = benefit * 0.07;

        // Create a new transaction
        const newTransaction = {
          totalBefore: totalSavingValue,
          totalAfter: totalSavingValue + benefit,
          fullBenefit: benefit,
          taxedBenefit: taxedBenefit,
          tax: tax,
          monthEA: eaValue,
          date: admin.firestore.Timestamp.now(),
          transactionType: 'benefit',
          description: 'benefit credit'
        };

        // Update the document by incrementing the montoTotal and adding the transaction
        batch.update(doc.ref, {
          montoTotal: admin.firestore.FieldValue.increment(taxedBenefit),
          transactions: admin.firestore.FieldValue.arrayUnion(newTransaction)
        });
      });

      // Commit the batch operation
      await batch.commit();

      console.log('Daily updates completed successfully.');
      return null;
    } catch (error) {
      console.error('Error updating ahorros:', error);
      throw new Error('Error updating ahorros: ' + error.message);
    }
    
    // Write your code above!
  });
Did you check FlutterFlow's Documentation for this topic?
Yes
1
5 replies