[javascript] code

Viewer

  1. exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
  2. // exports.scheduleAsyncMorningNotif = functions.pubsub.schedule("every 5 minutes")
  3.   .timeZone("America/Chicago")
  4.   .onRun((context) => {
  5.     const tsToMillis = admin.firestore.Timestamp.now().toMillis();
  6.     const today = new Date(tsToMillis + 15 * 60 * 60 * 1000);
  7.     const userPlants = db.collection("UserPlants");
  8.     var lastVisible = null;
  9.     // let totalSuccessCount = 0;
  10.     var multipleUsers = [];
  11.     function handleUserPlantsFCM() {
  12.       const snapshot = !!lastVisible
  13.         ? userPlants
  14.             .where("nextWatering", "<=", today)
  15.             .where("notificationsEnabled", "==", true)
  16.             .orderBy("nextWatering")
  17.             .startAfter(lastVisible)
  18.             .limit(500)
  19.             .get()
  20.         : userPlants
  21.             .where("nextWatering", "<=", today)
  22.             .where("notificationsEnabled", "==", true)
  23.             .orderBy("nextWatering")
  24.             .limit(500)
  25.             .get();
  26.       if (snapshot.size === 0) {
  27.         console.log("No matching documents.");
  28.         return;
  29.       }
  30.       snapshot.then(async function (querySnapshot) {
  31.         console.log(
  32.           "Query Snapshot of UserPlants showing as:",
  33.           querySnapshot.size
  34.         );
  35.         if (querySnapshot.size === 0) {
  36.           console.log("No matching documents.");
  37.           console.log(
  38.             "*****************************************Sending Messages*************************************************"
  39.           );
  40.           if (!!multipleUsers.length) {
  41.             const matchedMultipleUsers = multipleUsers.filter(
  42.               (plant) => plant.count > 2
  43.             );
  44.             if (!!matchedMultipleUsers.length) {
  45.               const matchedNotifications = matchedMultipleUsers.map(
  46.                 (plant) => ({
  47.                   notification: {
  48.                     title: `You have ${plant.count} plants to water! 🌱 `,
  49.                     body: `Your ${plant.plantName.toString()} needs some water - make sure to take care of it! ☔️`,
  50.                   },
  51.                   token: plant.userFCMToken,
  52.                 })
  53.               );
  54.               if (!!matchedNotifications && matchedNotifications.length) {
  55.                 try {
  56.                   admin
  57.                     .messaging()
  58.                     .sendAll(matchedNotifications)
  59.                     .then((response) => {
  60.                       const multipleSuccessCount = response.successCount;
  61.                       console.log(
  62.                         `${multipleSuccessCount} grouping messages are sent successfully.`
  63.                       );
  64.                       console.log(matchedMultipleUsers.length, matchedNotifications.length);
  65.                     });
  66.                 } catch (err) {
  67.                   console.log(err);
  68.                 }
  69.               } else {
  70.                 console.log("There is no any grouping messages to be sent!");
  71.               }
  72.             } else {
  73.               console.log("There is no any user who has multiple plants.");
  74.             }
  75.             const matchedOneOrTwoUsers = multipleUsers.filter(
  76.               (plant) => plant.count < 3
  77.             );
  78.             if (!!matchedOneOrTwoUsers.length) {
  79.               const matchedNotifications = matchedOneOrTwoUsers.map(
  80.                 (plant) => ({
  81.                   notification: {
  82.                     title: `You have a plant to save! 🌱 `,
  83.                     body: `Your ${plant.plantName.toString()} needs some water - make sure to take care of it! ☔️`,
  84.                   },
  85.                   token: plant.userFCMToken,
  86.                 })
  87.               );
  88.               if (!!matchedNotifications && matchedNotifications.length) {
  89.                 try {
  90.                   admin
  91.                     .messaging()
  92.                     .sendAll(matchedNotifications)
  93.                     .then((response) => {
  94.                       const multipleSuccessCount = response.successCount;
  95.                       console.log(
  96.                         `${multipleSuccessCount} messages are sent successfully.`
  97.                       );
  98.                       console.log(matchedOneOrTwoUsers.length, matchedNotifications.length);
  99.                     });
  100.                 } catch (err) {
  101.                   console.log(err);
  102.                 }
  103.               } else {
  104.                 console.log("There is no any messages to be sent!");
  105.               }
  106.             } else {
  107.               console.log("There is no any user who has a plant.");
  108.             }
  109.           }
  110.           return;
  111.         }
  112.         lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
  113.         // var messages = [];
  114.         querySnapshot.forEach((doc) => {
  115.           const data = doc.data();
  116.           const { plantName, userFCMToken, userRef } = data;
  117.           if (plantName && userFCMToken) {
  118.             // check if user does not exist in multiple users
  119.             if (!multipleUsers.some((plant) => plant.userRef === userRef)) {
  120.               let arr = [];
  121.               const userObj = {
  122.                 userRef: userRef,
  123.                 userFCMToken: userFCMToken,
  124.                 plantName: arr.push(plantName),
  125.                 count: 1,
  126.               };
  127.               console.log("==============NewUserPlant", plantName);
  128.               multipleUsers.push(userObj);
  129.             } else {
  130.               const existingUserPlant = multipleUsers.find(
  131.                 (plant) => plant.userRef === userRef
  132.               );
  133.               console.log(
  134.                 "++++++++++++++existingUserPlant:",
  135.                 existingUserPlant.plantName[0]
  136.               );
  137.               let arr = [];
  138.               const updatedUserPlant = {
  139.                 ...existingUserPlant,
  140.                 count: parseInt(existingUserPlant.count) + 1,
  141.                 plantName: Array.isArray(existingUserPlant.plantName)
  142.                   ? existingUserPlant.plantName.push(plantName)
  143.                   : [plantName],
  144.               };
  145.               const updatedMultipleUsers = multipleUsers.map((plant) => {
  146.                 if (plant.userRef === userRef) return updatedUserPlant;
  147.                 else return plant;
  148.               });
  149.               multipleUsers = updatedMultipleUsers;
  150.             }
  151.             // const message = {
  152.             //   notification: {
  153.             //     title: 'You have a plant to save! 🌱',
  154.             //     body: `Your ${plantName} needs some water - make sure to take care of it! ☔️`,
  155.             //   },
  156.             //   token: userFCMToken
  157.             // };
  158.             // messages.push(message);
  159.           } else {
  160.             console.log("Nil/false on user token, skipping for now");
  161.           }
  162.         });
  163.         // if (!!messages.length) {
  164.         //   try {
  165.         //     const response = await admin.messaging().sendAll(messages);
  166.         //     totalSuccessCount += response.successCount;
  167.         //   } catch (err) {
  168.         //     console.log(err);
  169.         //   }
  170.         //   messages = [];
  171.         // }
  172.         handleUserPlantsFCM();
  173.       });
  174.     }
  175.     handleUserPlantsFCM();
  176.     return;
  177.   });

Editor

You can edit this paste and save as new: