[javascript] grouping

Viewer

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

Editor

You can edit this paste and save as new: