Users can upload image afterwards, and it will update the same document, not create a new one.
LeaveRequestRepository:
package com.g4t4.home_cleaning_scheduler.repository;
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository {
code
@Autowired
public LeaveRequestRepository(Firestore firestore) {
super(firestore, "leave_requests");
}
public boolean saveLeaveRequest(LeaveRequest leaveRequest) {
return save(leaveRequest);
}
public void deleteLeaveRequest(LeaveRequest leaveRequest) {
delete(leaveRequest);
}
public CollectionReference getCollectionReference() {
return super.getCollectionReference();
}
// Additional methods to get leave requests by workerId, supervisorId, etc., can be added if needed.
To implement the desired adjustments in your leave request system—making the image upload optional during submission and allowing users to upload an image afterward that updates the existing document—you need to ensure that both the backend logic and Firestore interactions are correctly handled. I'll walk you through the necessary steps and provide code adjustments to achieve this.
1. Make Image Upload Optional During Submission
Current Implementation Review
Your current LeaveRequestController and LeaveRequestService already handle the medical certificate upload as optional:
The medicalCertificate parameter is marked as required = false, making it optional.
Service:
java
public boolean submitLeaveRequest(LeaveRequest leaveRequest, MultipartFile medicalCertificateFile) throws IOException {
if (leaveRequest.getLeaveType().equalsIgnoreCase("Medical")) {
if (medicalCertificateFile != null && !medicalCertificateFile.isEmpty()) {
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
}
}
// ...
}
The service checks if the medicalCertificateFile is present and only uploads it if available.
Ensure Proper Validation
Double-check that your validation logic aligns with making the upload optional. For example, if there are conditions where the medical certificate should be mandatory (e.g., for specific leave types), ensure that those conditions are correctly implemented.
No Further Changes Needed for Optional Upload
Given the current implementation, no additional changes are necessary to make the image upload optional during submission. However, ensure thorough testing to confirm that leave requests can be submitted without a medical certificate when appropriate.
2. Allow Users to Upload Image Afterwards and Update the Same Document
Ensure Unique Document Identification
To update an existing leave request with a medical certificate, it's crucial that each leave request has a unique identifier used as the document ID in Firestore. This ensures that updates target the correct document rather than creating a new one.
Repository Adjustment
Modify your LeaveRequestRepository to use the leaveRequestId as the document ID in Firestore. Assuming your AbstractFirestoreRepository supports such operations, ensure that the save method uses the leaveRequestId.
Here's how you can adjust the saveLeaveRequest method:
java
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository<LeaveRequest> {
@Autowired
public LeaveRequestRepository(Firestore firestore) {
super(firestore, "leave_requests");
}
public boolean saveLeaveRequest(LeaveRequest leaveRequest) {
try {
// Use leaveRequestId as the document ID
getCollectionReference().document(leaveRequest.getLeaveRequestId()).set(leaveRequest).get();
return true;
} catch (Exception e) {
// Log the exception
e.printStackTrace();
return false;
}
}
// Existing methods...
}
Explanation:
Using set with Document ID:
By calling getCollectionReference().document(leaveRequest.getLeaveRequestId()).set(leaveRequest), you ensure that the leave request is saved with a specific document ID corresponding to leaveRequestId. This allows for deterministic updates.
Handling Exceptions:
It's good practice to handle exceptions to prevent application crashes and provide meaningful feedback.
Service Adjustment
Your LeaveRequestService already includes a method to upload the medical certificate after the initial leave request submission. Ensure that this method correctly updates the existing document.
Here's your current implementation for reference:
java
public boolean uploadMedicalCertificate(String leaveRequestId, MultipartFile medicalCertificateFile) throws IOException, ExecutionException, InterruptedException {
if (medicalCertificateFile == null || medicalCertificateFile.isEmpty()) {
throw new IllegalArgumentException("Medical certificate image is required.");
}
// Retrieve existing leave request
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(leaveRequestId);
if (!optionalLeaveRequest.isPresent()) {
throw new IllegalArgumentException("Leave request not found.");
}
LeaveRequest leaveRequest = optionalLeaveRequest.get();
// Upload the image
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
// Update the leave request
return leaveRequestRepository.saveLeaveRequest(leaveRequest);
}
Recommendations:
Ensure leaveRequestRepository.get Retrieves by ID:
Make sure the get method retrieves the document by leaveRequestId.
Consistent Document ID Usage:
Ensure that both saveLeaveRequest and get methods use leaveRequestId as the document key to maintain consistency.
Controller Adjustment
Your LeaveRequestController provides an endpoint to upload the medical certificate after the initial submission. Ensure that this endpoint correctly invokes the service method to update the existing document.
Authentication & Authorization:
Make sure that only authorized users can upload medical certificates. For instance, verify that the user uploading the certificate is the owner of the leave request or has the necessary permissions.
Input Validation:
Validate the leaveRequestId and the uploaded file to prevent potential security vulnerabilities.
Firestore Security Rules (Optional but Recommended)
To enhance security, define Firestore security rules that enforce who can read or write to each leave request document. For example:
javascript
service cloud.firestore {
match /databases/{database}/documents {
match /leave_requests/{document} {
allow read: if request.auth != null && request.auth.uid == resource.data.workerId || request.auth.token.role == 'admin';
allow write: if request.auth != null && request.auth.uid == resource.data.workerId || request.auth.token.role == 'admin';
}
}
}
Explanation:
Read Access:
Allow the worker who created the leave request or an admin to read the document.
Write Access:
Allow only the worker or an admin to modify the document, including uploading the medical certificate.
3. Additional Recommendations
Ensure Atomic Operations
When updating the leave request with the medical certificate, ensure that the operation is atomic to prevent inconsistent states. Firestore's set operation with merge options can help achieve this.
For example, modify the saveLeaveRequest method to merge with existing data:
java
public boolean saveLeaveRequest(LeaveRequest leaveRequest) {
try {
// Use leaveRequestId as the document ID and merge with existing data
getCollectionReference()
.document(leaveRequest.getLeaveRequestId())
.set(leaveRequest, SetOptions.merge())
.get();
return true;
} catch (Exception e) {
// Log the exception
e.printStackTrace();
return false;
}
}
Explanation:
Set with Merge:
Using SetOptions.merge() ensures that only the fields provided in leaveRequest are updated, preserving other existing fields in the document.
Handle Concurrency
If multiple users might attempt to update the same leave request simultaneously, consider implementing concurrency controls to prevent race conditions. Firestore supports transactions that can help manage such scenarios.
Example using a transaction to update the medical certificate URL:
java
public boolean uploadMedicalCertificate(String leaveRequestId, MultipartFile medicalCertificateFile) throws IOException, ExecutionException, InterruptedException {
if (medicalCertificateFile == null || medicalCertificateFile.isEmpty()) {
throw new IllegalArgumentException("Medical certificate image is required.");
}
Firestore db = getFirestore();
DocumentReference leaveRequestRef = leaveRequestRepository.getCollectionReference().document(leaveRequestId);
ApiFuture<Void> transaction = db.runTransaction(trans -> {
DocumentSnapshot snapshot = trans.get(leaveRequestRef).get();
if (!snapshot.exists()) {
throw new IllegalArgumentException("Leave request not found.");
}
LeaveRequest leaveRequest = snapshot.toObject(LeaveRequest.class);
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
trans.set(leaveRequestRef, leaveRequest, SetOptions.merge());
return null;
});
transaction.get();
return true;
}
Explanation:
Transactions:
Using transactions ensures that the read and write operations are executed atomically, preventing conflicts from concurrent updates.
Enhance Error Handling and Logging
Implement comprehensive error handling and logging throughout your service and repository layers to aid in debugging and monitoring.
Example in LeaveRequestService:
java
public boolean uploadMedicalCertificate(String leaveRequestId, MultipartFile medicalCertificateFile) throws IOException, ExecutionException, InterruptedException {
if (medicalCertificateFile == null || medicalCertificateFile.isEmpty()) {
throw new IllegalArgumentException("Medical certificate image is required.");
}
try {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(leaveRequestId);
if (!optionalLeaveRequest.isPresent()) {
throw new IllegalArgumentException("Leave request not found.");
}
LeaveRequest leaveRequest = optionalLeaveRequest.get();
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
return leaveRequestRepository.saveLeaveRequest(leaveRequest);
} catch (Exception e) {
// Log the exception with more context
LoggerFactory.getLogger(LeaveRequestService.class).error("Error uploading medical certificate for leaveRequestId: {}", leaveRequestId, e);
throw e;
}
}
Testing
Thoroughly test both the submission without a medical certificate and the subsequent upload to ensure that:
Submissions without an image are handled correctly.
Uploads afterward correctly update the existing leave request without creating new documents.
Access controls are enforced appropriately.
Summary
By ensuring that the leaveRequestId is used as the document ID in Firestore and by handling both the optional upload during submission and the subsequent updates correctly, your system will function as intended. The provided code adjustments and recommendations aim to help you achieve a robust and secure implementation.
If you have any further questions or need additional assistance with specific parts of your implementation, feel free to ask!