Untitled

 avatar
coderalmamun
plain_text
7 days ago
2.3 kB
4
Indexable
async function sendExamExpiringReminderToStudents(isProduction) {
  const now = new Date();
  const currentDate = now.toISOString().split("T")[0]; // Format: YYYY-MM-DD

  let todayExams = [];
  let allStudents = [];

  const batchSnapshot = await (isProduction ? batchesProdCollection.get() : batchesTestCollection.get());

  for (const doc of batchSnapshot.docs) {
    const assignedLevelAndLessons = doc.data().assigned_exams || {};

    for (const levelAndLessonKey in assignedLevelAndLessons) {
      const topicExams = assignedLevelAndLessons[levelAndLessonKey];

      for (const topicExamKey in topicExams) {
        const topicExam = topicExams[topicExamKey];

        if (topicExam.expireDate === currentDate) {
          todayExams.push({
            ...topicExam,
            batch: doc.id, // Ensure batch ID is included
          });
        }
      }
    }
  }

  const studentSnapshot = await (isProduction ? userProdCollection : userTestCollection)
    .where("role", "==", "student")
    .where("accountStatus", "==", true)
    .get();

  for (const studentDoc of studentSnapshot.docs) {
    const studentData = studentDoc.data();

    allStudents.push({
      studentId: studentData.id,
      batch: studentData.batch,
      deviceToken: studentData.deviceToken,
    });
  }

  for (const exam of todayExams) {
    console.log("Today Exam:", exam);

    const batchStudents = allStudents.filter((student) => student.batch === exam.batch);

    const unSubmittedStudents = batchStudents.filter((student) => {
      console.log("Student ID:", student.studentId);
      return !exam.submissions.hasOwnProperty(student.studentId);
    });

    const deviceTokens = unSubmittedStudents.map((student) => student.deviceToken);
    console.log("Device Tokens:", deviceTokens);

    if (deviceTokens.length > 0) {
      const notificationData = {
        notification: {
          title: "Exam Deadline Reminder",
          body: `Your exam "${exam.examTitle}" will expire today. Please submit it before the deadline.`,
        },
        tokens: deviceTokens,
      };

      try {
        await admin.messaging().sendEachForMulticast(notificationData);
        console.log("Reminder notification sent successfully.");
      } catch (error) {
        console.error("Error sending reminder notification:", error);
      }
    }
  }
}
Editor is loading...
Leave a Comment