Untitled

 avatar
unknown
plain_text
4 days ago
2.2 kB
5
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 topicExam in topicExams) {
        const expireDate = topicExam.expireDate; // Format: "YYYY-MM-DD"

        if (expireDate === currentDate) {
          todayExams.push(topicExam);
        }
      }
    }
  }

  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: studentDoc.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) => !exam.submissions.has(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 your exam before the deadline.`,
        },
        tokens: deviceTokens,
      };

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