Help me adjust the code such that it checks the date of the request, just the day, month, and year match today's date. The date of request is stored as a timestamp in firebase.
Code context:
// LeaveRequestScheduler.java
package com.g4t4.home_cleaning_scheduler.service;
@Autowired
private LeaveRequestRepository leaveRequestRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private JavaMailSender emailSender;
@Scheduled(fixedRate = 60000) // Runs every minute
public void checkPendingMedicalLeaveRequests() {
System.out.println("Scheduled task started: checkPendingMedicalLeaveRequests");
try {
// Get today's date at midnight in UTC
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timestamp startOfToday = Timestamp.of(calendar.getTime());
// Set time to start of tomorrow
calendar.add(Calendar.DAY_OF_MONTH, 1);
Timestamp startOfTomorrow = Timestamp.of(calendar.getTime());
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection
.whereEqualTo("leaveType", "Medical")
.whereGreaterThanOrEqualTo("dateOfApplication", startOfToday)
.whereLessThan("dateOfApplication", startOfTomorrow)
.whereIn("medicalCertificateUrl", Arrays.asList(null, ""));
ApiFuture<QuerySnapshot> querySnapshot = query.get();
List<LeaveRequest> leaveRequests = querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
System.out.println("Number of pending medical leave requests found: " + leaveRequests.size());
for (LeaveRequest lr : leaveRequests) {
System.out.println("Processing LeaveRequest ID: " + lr.getLeaveRequestId());
// Get supervisorId
String supervisorId = lr.getSupervisorId();
if (supervisorId == null || supervisorId.isEmpty()) {
System.out.println("LeaveRequest ID " + lr.getLeaveRequestId() + " has no supervisorId");
continue;
}
// Get supervisor user
User supervisor = userRepository.findById(supervisorId);
if (supervisor == null) {
System.out.println("Supervisor not found for ID: " + supervisorId);
continue;
} else {
System.out.println("Supervisor found: " + supervisor.getName());
}
// Send email to supervisor
sendEmailToSupervisor(supervisor.getEmail(), lr);
}
} catch (Exception e) {
System.out.println("Exception occurred in scheduled task: " + e.getMessage());
e.printStackTrace();
}
}
private void sendEmailToSupervisor(String supervisorEmail, LeaveRequest leaveRequest) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(supervisorEmail);
message.setSubject("Pending Medical Leave Request - " + leaveRequest.getLeaveRequestId());
message.setText("Dear Supervisor,\n\n" +
"A medical leave request has been submitted by worker " + leaveRequest.getWorkerName() +
" (ID: " + leaveRequest.getWorkerId() + ") and requires a medical certificate.\n\n" +
"Please follow up with the worker to provide the necessary documentation.\n\n" +
"Best regards,\n" +
"Home Cleaning Scheduler System");
emailSender.send(message);
System.out.println("Email sent to supervisor: " + supervisorEmail);
} catch (Exception e) {
System.out.println("Failed to send email to supervisor: " + supervisorEmail);
e.printStackTrace();
}
}
}
To adjust your checkPendingMedicalLeaveRequests method so that it accurately checks whether the dateOfApplication matches today's date based on the day, month, and year, you should ensure that the timestamps used in your Firestore query correctly represent the start of today and the start of tomorrow in the desired timezone.
Using the java.time API (introduced in Java 8) is recommended for more precise and readable date and time handling. Below is the revised version of your method with detailed explanations:
java
// Import necessary classes
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import com.google.cloud.Timestamp;
@Scheduled(fixedRate = 60000) // Runs every minute
public void checkPendingMedicalLeaveRequests() {
System.out.println("Scheduled task started: checkPendingMedicalLeaveRequests");
try {
// 1. Define the timezone for date comparison
// Replace ZoneId.systemDefault() with a specific timezone if needed, e.g., ZoneId.of("America/New_York")
ZoneId zoneId = ZoneId.systemDefault();
// 2. Get today's date in the specified timezone
LocalDate today = LocalDate.now(zoneId);
// 3. Calculate the start of today (midnight)
ZonedDateTime startOfTodayZDT = today.atStartOfDay(zoneId);
Instant startOfTodayInstant = startOfTodayZDT.toInstant();
Timestamp startOfToday = Timestamp.fromMillis(startOfTodayInstant.toEpochMilli());
// 4. Calculate the start of tomorrow (midnight)
LocalDate tomorrow = today.plusDays(1);
ZonedDateTime startOfTomorrowZDT = tomorrow.atStartOfDay(zoneId);
Instant startOfTomorrowInstant = startOfTomorrowZDT.toInstant();
Timestamp startOfTomorrow = Timestamp.fromMillis(startOfTomorrowInstant.toEpochMilli());
// Debugging output
System.out.println("Start of Today (UTC): " + startOfToday);
System.out.println("Start of Tomorrow (UTC): " + startOfTomorrow);
// 5. Build the Firestore query to fetch leave requests from today
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection
.whereEqualTo("leaveType", "Medical")
.whereGreaterThanOrEqualTo("dateOfApplication", startOfToday)
.whereLessThan("dateOfApplication", startOfTomorrow)
.whereIn("medicalCertificateUrl", Arrays.asList(null, ""));
// 6. Execute the query
ApiFuture<QuerySnapshot> querySnapshot = query.get();
// 7. Map the query results to LeaveRequest objects
List<LeaveRequest> leaveRequests = querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
System.out.println("Number of pending medical leave requests found: " + leaveRequests.size());
// 8. Process each leave request
for (LeaveRequest lr : leaveRequests) {
System.out.println("Processing LeaveRequest ID: " + lr.getLeaveRequestId());
// Retrieve supervisorId from the leave request
String supervisorId = lr.getSupervisorId();
if (supervisorId == null || supervisorId.isEmpty()) {
System.out.println("LeaveRequest ID " + lr.getLeaveRequestId() + " has no supervisorId");
continue;
}
// Fetch the supervisor's user details
User supervisor = userRepository.findById(supervisorId);
if (supervisor == null) {
System.out.println("Supervisor not found for ID: " + supervisorId);
continue;
} else {
System.out.println("Supervisor found: " + supervisor.getName());
}
// Send an email notification to the supervisor
sendEmailToSupervisor(supervisor.getEmail(), lr);
}
} catch (Exception e) {
System.out.println("Exception occurred in scheduled task: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Sends an email to the supervisor regarding the pending medical leave request.
*
* @param supervisorEmail The email address of the supervisor.
* @param leaveRequest The leave request details.
*/
private void sendEmailToSupervisor(String supervisorEmail, LeaveRequest leaveRequest) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(supervisorEmail);
message.setSubject("Pending Medical Leave Request - " + leaveRequest.getLeaveRequestId());
message.setText("Dear Supervisor,\n\n" +
"A medical leave request has been submitted by worker " + leaveRequest.getWorkerName() +
" (ID: " + leaveRequest.getWorkerId() + ") and requires a medical certificate.\n\n" +
"Please follow up with the worker to provide the necessary documentation.\n\n" +
"Best regards,\n" +
"Home Cleaning Scheduler System");
emailSender.send(message);
System.out.println("Email sent to supervisor: " + supervisorEmail);
} catch (Exception e) {
System.out.println("Failed to send email to supervisor: " + supervisorEmail);
e.printStackTrace();
}
}
Detailed Explanation:
Timezone Configuration:
ZoneId: It's crucial to define the correct timezone based on your application's requirements. Using ZoneId.systemDefault() ensures that the application uses the server's default timezone. If your users are in a specific timezone, replace it with ZoneId.of("Desired/Timezone"), for example, ZoneId.of("America/New_York").
Calculating Start and End Timestamps:
Start of Today: today.atStartOfDay(zoneId) sets the time to midnight (00:00) of the current day in the specified timezone.
Start of Tomorrow: By adding one day to today and setting the time to midnight, you define the exclusive upper bound for today's date.
Timestamp Conversion: Firestore uses its own Timestamp class. Timestamp.fromMillis() converts the Instant to Firestore's Timestamp by using the epoch milliseconds.
Firestore Query:
whereGreaterThanOrEqualTo & whereLessThan: These ensure that only documents with dateOfApplication between the start of today and the start of tomorrow are retrieved. This effectively captures all leave requests made today regardless of the exact time.
whereIn for medicalCertificateUrl: This filters leave requests that either don't have a medicalCertificateUrl or it's empty, indicating that the certificate hasn't been provided yet.
Processing Leave Requests:
For each fetched LeaveRequest, the scheduler retrieves the supervisor's details and sends an email notification.
Error Handling:
Comprehensive try-catch blocks ensure that any exceptions during the scheduled task or email sending process are logged for troubleshooting.
Additional Recommendations:
Use of Indexes: Ensure that Firestore has the appropriate indexes for the queries you're performing, especially since you're using multiple where clauses. Firestore might prompt you to create necessary indexes if they don't exist.
Time Synchronization: Ensure that your server's clock is synchronized, especially if it's critical for the application to handle dates accurately.
Email Throttling: If there's a possibility of a large number of leave requests, consider implementing throttling or batching mechanisms to handle the email sending more efficiently and to avoid potential issues with your email service provider.
Logging Framework: Instead of using System.out.println, consider using a logging framework like SLF4J with Logback or Log4j for more flexible and configurable logging.
By implementing the above changes, your scheduler will accurately fetch and process leave requests that match today's date based on the day, month, and year, ensuring that only relevant requests are handled each minute.